<?php
use Zend\Console\Prompt\Char;
defined ( 'IN_TS' ) or die ( 'Access Denied.' );
//PHP异步
function dophp($url,$para=array()){
    $urlinfo = parse_url($url);
    $host = $urlinfo['host'];
    $path = $urlinfo['path'];
    $query=isset($para) ? http_build_query($para) : '';
    $port = 80;
    $errno = 0;
    $errstr = '';
    $timeout = 10;

    $fp = fsockopen($host, $port, $errno, $errstr, $timeout);
    if(!$fp){
        return false;
    }

    $out = "POST ".$path." HTTP/1.1\r\n";
    $out .= "host:".$host."\r\n";
    $out .= "content-length:".strlen($query)."\r\n";
    $out .= "content-type:application/x-www-form-urlencoded\r\n";
    $out .= "connection:close\r\n\r\n";
    $out .= $query;
    fputs($fp, $out);
    //     while($row=fread($fp, 4096)){
    //         $response .= $row;
    //     }
    fclose($fp);
    //     $pos = strpos($response, "\r\n\r\n");
    //     $response = substr($response, $pos+4);
    //     return $response;
    return true;
}
//解压缩
function gymunzip($file){
	$fl=explode('.', $file);
	unset($fl[count($fl)-1]);
	$fu=implode('.', $fl);
	$zp=new ZipArchive();
	if($zp->open($file)==TRUE){
		$zp->extractTo($fu);
		$zp->close();
		return $fu;
	}else{
		return $file;
	}
}
//去除几个g一维数组相同项
function delarray_value($arr1,$arr2=null,$arr3=null,$arr4=null,$arr5=null,$darr=Array()){
	if($arr2==null){
		if(count($darr)==0){
			return array_unique(array_filter($arr1));
		}else{
			for($i=count($arr1)-1;$i>=0;$i--){
				if(in_array($arr1[$i], $darr)){
					array_splice($arr1, $i,1);
				}
			}
			return array_unique(array_filter($arr1));
		}
	}
	for($i=count($arr1)-1;$i>=0;$i--){
		$arr=$arr1;
		unset($arr[$i]);
		if(in_array($arr1[$i], $arr)||in_array($arr1[$i], $darr)){
			array_splice($arr1, $i,1);
			array_splice($arr2, $i,1);
			if($arr3!=null){
				array_splice($arr3, $i,1);
			}
			if($arr4!=null){
				array_splice($arr4, $i,1);
			}
			if($arr5!=null){
				array_splice($arr5, $i,1);
			}
		}
	}
	return array($arr1,$arr2,$arr3,$arr4,$arr5);
}
function mixqx($str1,$str2){
	if($str1==''){
		return $str2;
	}
	if($str2==''){
		return $str1;
	}
	$arr1=explode(',', $str1);
	$arr2=explode(',', $str2);
	$arr=array_merge($arr1,$arr2);
	return implode(',', array_unique($arr));
}

function jpush($rid,$id,$con,$ty=0){
	require_once(THINKROOT."/jpushSDK/conf.php");
	if($ty==0){
	    $response = $client->push()
	    ->setPlatform(array('ios', 'android'))
	    ->addTag($rid)
	    ->setNotificationAlert('Hi, JPush')
	    ->iosNotification($con, array(
	        'sound' => 'sound.caf',
	        'badge' => '+1',
	        'extras' => array(
	            'id' => $id,
	        ),
	    ))
	    ->androidNotification($con, array(
	        'extras' => array(
	            'id' => $id,
	        ),
	    ))
	    ->options(array(
	        'apns_production' => false,
	    ))
	    ->send();
	}elseif($ty==1){
	    $response = $client->push()
	    ->setPlatform(array('ios', 'android'))
	    ->addAlias($rid)
	    ->setNotificationAlert('Hi, JPush')
	    ->iosNotification($con, array(
	        'sound' => 'sound.caf',
	        'badge' => '+1',
	        'extras' => array(
	            'id' => $id,
	        ),
	    ))
	    ->androidNotification($con, array(
	        'extras' => array(
	            'id' => $id,
	        ),
	    ))
	    ->options(array(
	        'apns_production' => false,
	    ))
	    ->send();
	}
	return $response;
}
function sendEmail($to,$subject,$body,$cc='',$att=''){
    global $fd_domain;
    $da=array(
        'to'=>$to,
        'subject'=>$subject,
        'body'=>$body,
        'cc'=>$cc,
        'att'=>$att
    );
    $url=$fd_domain.'index.php?ac=ajax&ts=sendmail';
    $ch=curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $da);
    $l=curl_exec($ch);
    curl_close($ch);
    return true;
}
//删除缓存
function delkeys($str){
	$arr=R()->keys($str);
	foreach ($arr as $v){
		R()->delete($v);
	}
	return true;
}
//生成二维码
function geturlpic($url,$size=3,$pnm=false,$logo=false){
// 	include 'phpqrcode.php';
	require_once THINKROOT.'/phpqrcode/phpqrcode.php';
	if($pnm!=false){
		$fl='/pic/contract/'.$pnm;
		$pnm=THINKROOT.'/pic/contract/'.$pnm;
		QRcode::png($url,$pnm,'L',$size);
		if($logo==false){
			return $fl;
		}else{
			$QR = imagecreatefromstring(file_get_contents($pnm));
			$logo = imagecreatefromstring(file_get_contents(THINKROOT.$logo));
			$QR_width = imagesx($QR);//二维码图片宽度
			$QR_height = imagesy($QR);//二维码图片高度
			$logo_width = imagesx($logo);//logo图片宽度
			$logo_height = imagesy($logo);//logo图片高度
			$logo_qr_width = $QR_width / 7;
			$scale = $logo_width/$logo_qr_width;
			$logo_qr_height = $logo_height/$scale;
			$from_width = ($QR_width - $logo_qr_width) / 2;
			//重新组合图片并调整大小
			imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width,
			$logo_qr_height, $logo_width, $logo_height);
			imagepng($QR, $pnm);
			return $fl;
		}
	}else{
		return QRcode::png($url,$pnm,'L',$size);
	}
}
function getleftmenu($ot,$m,$n=-1){
	global $gym_header;
	$out=='';
	if($n>=0){
		if($gym_header[$m]['url'][$n]==$ot){
			$out=' class="action"';
		}
	}else{
		foreach ($gym_header[$m]['url'] as $va){
			if($va==$ot){
				$out=' in';
			}
		}
	}
	return $out;
}

//FINDEN权限
function fdadmin($str,$uid,$isadmin=0){
// 	return true;
	if(R()->exists("gymchina:$uid")){
		$_padminh=R()->hGetAll("gymchina:$uid");
	}else{
		return false;
	}
	if($_padminh['isadmin']==99){
		return true;
	}
	if($_padminh['isadmin']!=99 && $isadmin==99){
		return false;
	}
	if($_padminh['isadmin']==98||$_padminh['isadmin']==97){
		return true;
	}
	if($_padminh['isadmin']==0){
		return false;
	}
	$adminflag=explode(',', $_padminh['adminflag']);
	if(in_array($str, $adminflag)){
		return true;
	}else{
		$arr=explode(':', $str);
		$strc=$arr[0].':'.$arr[1].':99';
		if(in_array($strc, $adminflag)){
			return true;
		}else{
			return false;
		}
	}
}
//根据秒数获取小时
function gettimefrs($sec){
	if($sec==''||$sec==0){
		return 0;
	}
	if($sec<60){
		return $sec.'秒';
	}
	if($sec<3600){
		if($sec%60==0){
			return ($sec/60).'分钟';
		}
		return intval($sec/60).'分'.($sec%60).'秒';
	}else{
		$yl=$sec%3600;
		if($yl==0){
			return ($sec/3600).'小时';
		}
		if($yl%60==0){
			return intval($sec/3600).'小时'.($yl/60).'分';
		}
		return intval($sec/3600).'小时'.intval($yl/60).'分'.($yl%60).'秒';
	}
}
//获取两个时间戳所差月份（每月一号时间戳）、周数（每周一时间戳）
function gettimediff($stm,$etm,$ty=1){
	$i=0;
	$tm=$stm;
	if($ty==1){//月份
		while($tm<$etm){
			$tm=strtotime(date('Y-m-d',strtotime("1 month",$tm)));
			$i++;
		}
	}elseif($ty==2){
		while($tm<$etm){
			$tm=strtotime(date('Y-m-d',strtotime("1 week",$tm)));
			$i++;
		}
	}
	return $i;
}
//获取空余时段
function getkctimer($arr){
	for($i=1;$i<49;$i++){
		foreach ($arr as $v){
			if($i>$v['min'] && $i<$v['max']){
				$hs[]=$i;
			}
		}
	}
	for($i=1;$i<49;$i++){
		if(!in_array($i, $hs)){
			$ot[]=$i;
		}
	}
	$out=array();
	foreach ($ot as $v){
		$k=$v+1;
		$j=$v+2;
		$l=$v+3;
		if(in_array($k, $ot) && in_array($j, $ot) && in_array($j, $ot) && in_array($l, $ot)){
			$out[]=$v;
			$out[]=$k;
			$out[]=$j;
			$out[]=$l;
		}
	}
	$out=array_unique($out);
	return $out;
}
function gettimestr($tm){
	$tc=explode(':', $tm);
	unset($tc[2]);
	return implode(':', $tc);
}

function exceltime($date){
// 	$date=$date>25568 ? $date : 25569;
// 	$ofs=(70*365+17+2)*86400;
// 	$out=date('Y-m-d',$date*86400-$ofs);
	$ot=($date-25569)*86400;
	$out=date('Y-m-d',$ot);
	return $ot;
}
function convertstr($str){
	$len=strlen($str);
	$ot=substr($str, 0,$len-4);
	return $ot.'XXXX';
}

//去除CURL过来内容的BOM
function delbom($str){
	if(substr($str,0,3)=="\xEF\xBB\xBF"){
		$oput=substr($str,3);
	}
	return $oput;
}
//判断是否手机端
function isMobile() {
	// 如果有HTTP_X_WAP_PROFILE则一定是移动设备
	if (isset ( $_SERVER ['HTTP_X_WAP_PROFILE'] )) {
		return true;
	}
	// 如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
	if (isset ( $_SERVER ['HTTP_VIA'] )) {
		// 找不到为flase,否则为true
		return stristr ( $_SERVER ['HTTP_VIA'], "wap" ) ? true : false;
	}
	// 脑残法，判断手机发送的客户端标志,兼容性有待提高
	if (isset ( $_SERVER ['HTTP_USER_AGENT'] )) {
		$clientkeywords = array ('nokia', 'sony', 'ericsson', 'mot', 'samsung', 'htc', 'sgh', 'lg', 'sharp', 'sie-', 'philips', 'panasonic', 'alcatel', 'lenovo', 'iphone', 'ipod', 'blackberry', 'meizu', 'android', 'netfront', 'symbian', 'ucweb', 'windowsce', 'palm', 'operamini', 'operamobi', 'openwave', 'nexusone', 'cldc', 'midp', 'wap', 'mobile' );
		// 从HTTP_USER_AGENT中查找手机浏览器的关键字
		if (preg_match ( "/(" . implode ( '|', $clientkeywords ) . ")/i", strtolower ( $_SERVER ['HTTP_USER_AGENT'] ) )) {
			return true;
		}
	}
	// 协议法，因为有可能不准确，放到最后判断
	if (isset ( $_SERVER ['HTTP_ACCEPT'] )) {
		// 如果只支持wml并且不支持html那一定是移动设备
		// 如果支持wml和html但是wml在html之前则是移动设备
		if ((strpos ( $_SERVER ['HTTP_ACCEPT'], 'vnd.wap.wml' ) !== false) && (strpos ( $_SERVER ['HTTP_ACCEPT'], 'text/html' ) === false || (strpos ( $_SERVER ['HTTP_ACCEPT'], 'vnd.wap.wml' ) < strpos ( $_SERVER ['HTTP_ACCEPT'], 'text/html' )))) {
			return true;
		}
	}
	return false;
}

//二维数据去维去重
function dw_array($arr){
	if(!is_array($arr)){
		return $arr;
	}
	foreach ($arr as $v){
		if(!is_array($v)){
			return array_unique(array_filter($arr));
		}
		if(count($arr)==1){
			return array_unique(array_filter($v));
		}
		$ops=array_unique(array_filter($v));
// 		$op[]=array_filter($v);
// 		if(count($ops)>0){
			$op[]=$ops;
// 		}
	}
	return $op;
}
/*统计图：线形图
 * $data=>数据;$bz=>X轴标识;$w,$h=>图宽高;$title=>主标题,副标题和X轴标识,Y轴标识;$filename=>图片存储位置;
* $arr=>每种颜色的标识
*/
function imgline($data,$bz,$w,$h,$title,$filename,$arr,$isty=0){
	require_once THINKROOT.'/jpgraph/jpgraph.php';
	require_once THINKROOT.'/jpgraph/jpgraph_line.php';
	require_once THINKROOT.'/jpgraph/jpgraph_bar.php';

	$color=array('blue','darkred','orange','green','yellow','black','red','brwn','grey');

	$imgfile=THINKROOT.$filename;
	$graph = new Graph($w,$h);
	$graph->SetScale("textlin");
	if($isty==0){
		$graph->img->SetMargin(50,150,60,50);
	}else{
		$graph->img->SetMargin(50,50,60,100);
	}
	$graph->title->Set($title[0]);
	$graph->title->SetFont(FF_SIMSUN,FS_BOLD,16);
	$graph->subtitle->Set($title[1]);
	$graph->subtitle->SetFont(FF_SIMSUN);
	$graph->xaxis->title->Set($title[2]);
	$graph->yaxis->title->Set($title[3]);
	$graph->yaxis->title->SetFont( FF_SIMSUN , FS_BOLD );
	$graph->xaxis->title->SetFont( FF_SIMSUN , FS_BOLD );
	$graph->xaxis->SetTickLabels($bz);
	$graph->xaxis->SetFont(FF_SIMSUN);
	$graph->legend->SetFont(FF_SIMSUN);
	if($isty==1){
	$graph->legend->SetLayout(LEGEND_HOR);
	$graph->legend->Pos(0.4,0.95,"center","bottom");
	}
	$graph->SetShadow();

	foreach ($data as $k=>$v){
		$llot[$k]=new LinePlot($v);
		$llot[$k]->SetLegend($arr[$k]);
		$llot[$k]->SetColor($color[$k]);
		$llot[$k]->value->show();
		$llot[$k]->value->SetColor($color[$k]);
		$graph->Add($llot[$k]);
	}
	$graph->Stroke($imgfile);
}

/*统计图：柱形单图
 * $data=>数据;$bz=>X轴标识;$w,$h=>图宽高;$title=>主标题和X轴标识;$filename=>图片存储位置;
 * $arr=>缩放、颜色、柱形大小
 */
function imgbar($data,$bz,$w,$h,$title,$filename,$arr){
	require_once THINKROOT.'/jpgraph/jpgraph.php';
	require_once THINKROOT.'/jpgraph/jpgraph_line.php';
	require_once THINKROOT.'/jpgraph/jpgraph_bar.php';

	$imgfile=THINKROOT.$filename;
	$graph = new Graph($w,$h,'auto');
	$graph->img->SetMargin(40,30,50,40);
	$graph->SetScale("textint");
	$graph->SetShadow();
	$graph->SetFrame(false);

	$graph->yaxis->scale->SetGrace($arr[0]);

	$graph->xaxis->SetTickLabels($bz);
	$graph->xaxis->SetFont(FF_SIMSUN);

	$graph->title->Set($title[0]);
	$graph->title->SetFont(FF_SIMSUN,FS_BOLD,16);
	$graph->xaxis->title->Set($title[1]);
	$graph->xaxis->title->SetFont(FF_SIMSUN,FS_BOLD);

	$bplot = new BarPlot($data);
	$bplot->SetFillColor($arr[1]);
	$bplot->SetWidth($arr[2]);
	$bplot->SetShadow();

	$bplot->value->Show();
	$bplot->value->SetFont(FF_SIMSUN,FS_BOLD);
	$bplot->value->SetAngle(45);
	$bplot->value->SetColor("black","darkred");
	$graph->Add($bplot);

	$graph->Stroke($imgfile);
}

/*统计图：柱形双图
 * $data1,$data2=>数据;$bz=>X轴标识;$w,$h=>图宽高;$title=>主标题和X轴标识;$filename=>图片存储位置;
* $arr=>缩放、颜色、柱形大小
*/
function imgbars($data1,$data2,$bz,$w,$h,$title,$filename,$arr){
	require_once THINKROOT.'/jpgraph/jpgraph.php';
	require_once THINKROOT.'/jpgraph/jpgraph_line.php';
	require_once THINKROOT.'/jpgraph/jpgraph_bar.php';

	foreach ($data1 as $v){
		$data[]=0;
	}

	$imgfile=THINKROOT.$filename;
	$graph = new Graph(800,600);
	$graph->img->SetMargin(40,40,50,40);
	$graph->title->Set($title[0]);
	$graph->title->SetFont(FF_SIMSUN,FS_BOLD,16);

	// Setup Y and Y2 scales with some "grace"
	$graph->SetScale("textlin");
	$graph->SetY2Scale("lin");
	$graph->yaxis->scale->SetGrace($arr[0]);
	$graph->y2axis->scale->SetGrace($arr[1]);

	$graph->xaxis->SetTickLabels($bz);
	$graph->xaxis->SetFont(FF_SIMSUN);
	$graph->xaxis->title->Set($title[1]);
	$graph->xaxis->title->SetFont(FF_SIMSUN,FS_BOLD);

	$graph->ygrid->Show(true,true);
	$graph->ygrid->SetColor('gray','lightgray@0.5');

	$graph->SetMarginColor('white');
	$graph->y2axis->SetColor('darkred');

	$bplotzero = new BarPlot($data);

	$ybplot1 = new BarPlot($data1);
	$ybplot1->value->Show();
	$ybplot1->value->SetColor($arr[2]);
	$ybplot1->SetFillColor($arr[2]);
	$ybplot = new GroupBarPlot(array($ybplot1,$bplotzero));

	$ybplot2 = new BarPlot($data2);
	$ybplot2->value->Show();
	$ybplot2->value->SetColor($arr[3]);
	$ybplot2->SetFillColor($arr[3]);
	$y2bplot = new GroupBarPlot(array($bplotzero,$ybplot2));

	$graph->Add($ybplot);
	$graph->AddY2($y2bplot);

	$graph->Stroke($imgfile);
}

//changedata  0:测试 1主库 2从库
function changedata($i){
	include THINKROOT.'/data/config.inc.php';
	if($i==0){
		$data=$DB_test;
	}elseif($i==1){
		$data=$DB_pro;
	}elseif($i==2){
		$data=$DB_pro1;
	}
	$db=new MySql($data);
	return $db;
// 	return $data;
}
//PHPExcel
function upexcel($filename,$ty=0){
	require_once THINKROOT.'/class/PHPExcel.php';
	require_once THINKROOT.'/class/PHPExcel/IOFactory.php';
	require_once THINKROOT.'/class/PHPExcel/Reader/Excel5.php';
	require_once THINKROOT.'/class/PHPExcel/Reader/Excel2007.php';
	if($ty==1){
		$ety='Excel2007';
	}else{
		$ety='Excel5';
	}
	$objReader=PHPExcel_IOFactory::createReader($ety);
	$objPhpExcel=new PHPExcel();
	$objPhpExcel=$objReader->load($filename);
// 	return $filename;

	$sheet=$objPhpExcel->getSheet(0);
	$rows=$sheet->getHighestRow();
	$cols=PHPExcel_Cell::columnIndexFromString($sheet->getHighestColumn());
	$letter=array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');
	for($k=0;$k<=$cols;$k++){
		$value=$objPhpExcel->getActiveSheet()->getCellByColumnAndRow($k,1)->getValue();
		if(empty($value)){
			break;
		}
		$y=$k;
	}
	$opt[0]=$y;
	for($i=1;$i<=$rows;$i++){
		$value=$objPhpExcel->getActiveSheet()->getCellByColumnAndRow(0,$i)->getValue();
		if(empty($value)){
			continue;
		}
		for($j=0;$j<=$y;$j++){
			$opt[$i][$j]=$objPhpExcel->getActiveSheet()->getCellByColumnAndRow($j,$i)->getValue();
			if(is_object($opt[$i][$j])){
				$opt[$i][$j]=$opt[$i][$j]->__toString();
			}
		}
	}
	return $opt;
}
function upexcel1($filename){
    require_once 'Excel/reader.php';
    $data = new Spreadsheet_Excel_Reader();
    $data->setOutputEncoding('utf-8');
    $data->setUTFEncoder('mb');
    $data->read($filename);
    $opt[0]=$data->sheets[0]['numCols'];
    for ($i = 2; $i <= $data->sheets[0]['numRows']; $i++) {
        for ($j = 1; $j <= $data->sheets[0]['numCols']; $j++) {
            if(isset($data->sheets[0]['cells'][$i][$j])){
                $opt[$i][$j]= $data->sheets[0]['cells'][$i][$j];
            }
        }
    }
    return $opt;
}
function downexcel($data,$title,$filename='导出数据',$w=20){
	require_once THINKROOT.'/class/PHPExcel.php';
	require_once THINKROOT.'/class/PHPExcel/IOFactory.php';
	require_once THINKROOT.'/class/PHPExcel/Writer/Excel5.php';
	require_once THINKROOT.'/class/PHPExcel/Writer/Excel2007.php';

	$objexcel=new PHPExcel();
// 	return $filename;
	$letter=array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');
	if($title){
		$i=0;
		foreach ($title as $v){
			$index=$letter[$i]."1";
			$ind=$letter[$i];
			$objexcel->setActiveSheetIndex(0)->getColumnDimension($ind)->setWidth($w);
			$objexcel->setActiveSheetIndex(0)->setCellValue($index,$v);
			$i++;
		}
	}
	if($data){
		$i=2;
		foreach ($data as $k=>$v){
			$j=0;
			foreach ($v as $va){
				$index=$letter[$j].$i;
// 				if($j==0){
// 					$objexcel->getActiveSheet()->setCellValueExplicit($index,$va,PHPExcel_Cell_DataType::TYPE_STRING);
					$objexcel->setActiveSheetIndex(0)->setCellValueExplicit($index,$va,PHPExcel_Cell_DataType::TYPE_STRING);
// 				}else{
// 					$objexcel->setActiveSheetIndex(0)->setCellValue($index,$va);
// 				}
				$j++;
			}
			$i++;
		}
	}
	$objexcel->getActiveSheet()->setTitle($filename);
	$objexcel->setActiveSheetIndex(0);

	ob_end_clean();
// 	header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
	header("Content-Type: application/octet-stream");
	header('Content-Type: application/vnd.ms-excel');
	header("Content-Transfer-Encoding: binary");
	header('Content-Disposition: attachment;filename="'.$filename.'.xls"');
// 	header('Cache-Control: max-age=0');
	header("Pragma: no-cache");

	$objwrite=PHPExcel_IOFactory::createWriter($objexcel,"Excel5");
	$objwrite->save('php://output');
}
function downexcel1($data,$title,$filename='导出数据'){
    header("Content-Type: application/octet-stream");
    header('Content-Type: application/vnd.ms-excel');
    header("Content-Transfer-Encoding: binary");
    header('Content-Disposition: attachment;filename="'.$filename.'.xls"');
    foreach ($title as $v){
        echo mb_convert_encoding($v, 'gb2312').chr(9);
    }
    echo chr(13);
    foreach ($data as $v){
        foreach ($v as $va){
            echo mb_convert_encoding($va, 'gb2312').chr(9);
        }
        echo chr(13);
    }
}
//redis
function R(){
	$mredis=new Redis();
	$mredis->connect('127.0.0.1',6379);
	$mredis->auth('4k6CyKZSPw0f');
	return $mredis;
}
function D(){
	$mredis=new Redis();
	$mredis->connect('127.0.0.1',6380);
// 	$mredis->auth('xxx');
	return $mredis;
}
function requireclass($classname){
	global $db;
	$MT_CF=include THINKROOT.'/thinksaas/configclass.php';
	if(isset($MT_CF['xhtclass'][$classname])){
		require_once THINKROOT.$MT_CF['xhtclass'][$classname];
		return new $classname($db);
	}
	unset($db);
}
function getrandstr($num){
	$arr=array('A','B','C','D','1','5','3','E','F','0','2','G','H','I','J','K','4','6','L','M','N','O','P','Q','7','8','9','Q','R','S','T','U','V','1','3','2','W','X','Y','Z','8','0','1','2','3','4','5','6','7','8','9','0','1','2','3','4','5','6','7','8','9','0','1','2','3','4','5','6','7','8','9','0','1','2','3','4','5','6','7','8','9','0','1','2','3','4','5','6','7','8','9');
	$str='';
	for($i=0;$i<$num;$i++){
		$str.=$arr[rand(0, 90)];
	}
	return $str;
}

//管理权限认证
function gymadmin($isadmin,$role=array('0'),$str=array('99')){
	$gym_useridh=isset($_COOKIE['gym_userid']) ? intval($_COOKIE['gym_userid']) : 0;
	//admin redis
	if(R()->exists("gym_playabc:$gym_useridh")){
		$_padminh=R()->hGetAll("gym_playabc:$gym_useridh");
	}
	if(!isset($_padminh)){
		return false;
	}
	if($_padminh['isadmin']<$isadmin){
		return false;
	}
	if($isadmin<3 && $_padminh['dcid']==0){
		return false;
	}
	if($isadmin>2 && $_padminh['dcid']>0){
		return false;
	}
	if($_padminh['isadmin']>=9){
		if($isadmin<3){
			if($_padminh['dcid']==0){
				return false;
			}else{
				return true;
			}
		}else{
			if($_padminh['dcid']==0){
				return true;
			}else{
				return false;
			}
		}
	}elseif($_padminh['isadmin']<3){
		if($_padminh['cid']!=$_padminh['dcid']){
			return false;
		}else{
			if($_padminh['isadmin']<2){
				if(in_array($_padminh['roletype'], $role)){
					return true;
				}else{
					return false;
				}
			}else{
				return true;
			}
		}
	}elseif($_padminh['isadmin']==3){
		$croles=array();
		$croles=explode(',', $_padminh['crole']);
		if(count($croles)==0 && $_padminh['dcid']!=0){
			return false;
		}
		foreach ($croles as $v){
			$b=explode('|', $v);
			$c[]=$b[0];
			$rc[]=$b[1];
		}
		if($_padminh['dcid']!=0){
			if(!in_array($_padminh['dcid'], $c)){
				return false;
			}else{
				$k=array_keys($c,$_padminh['dcid']);
				$rl=$rc[$k];
				if($rl==0){
					return true;
				}else{
					if(in_array($rl, $role)){
						return true;
					}else{
						return false;
					}
				}
			}
		}else{
			$gym_isadmin3=0;
			foreach ($rc as $v){
				if(in_array($v, $role)){
					$gym_isadmin3=1;
					break;
				}
			}
			if($gym_isadmin3==0){
				return false;
			}else{
				return true;
			}
		}
	}elseif($_padminh['isadmin']==8){
		$adminflag=explode(',', $_padminh['adminflag']);
		if(count($str)==1 && $str[0]=='99'){
			return true;
		}
		$isgymadmin=0;
		foreach ($str as $v){
			if(in_array($v, $adminflag)){
				$isgymadmin=1;
				break;
			}
		}
		if($isgymadmin==1){
			return true;
		}else{
			return false;
		}
	}else{
		return true;
	}

}

function shadmin($str=null){
	if(!isset($_padmin)){
		return false;
	}else{
		if($_padmin['isadmin']>2){
			return true;
		}else{
			if($str==null){
				return true;
			}else{
				if(substr_count($_padmin['adminflag'], $str)>0){
					return true;
				}else{
					return false;
				}
			}
		}
	}
}

function shadmins($str){
	if(!isset($_padmin)){
		return false;
	}else{
		if($_padmin['isadmin']>2){
			return true;
		}else{
			if($str<10){
				for($i=1;$i<=$str;$i++){
					$ar='0'.$i;
					if(substr_count($_padmin['adminflag'], $ar)>0){
						return true;
						break;
					}
				}
				return false;
			}else{
				$j=intval($str/10)*10+1;
				for($i=$j;$i<=$str;$i++){
					if(substr_count($_padmin['adminflag'], $i)>0){
						return true;
						break;
					}
				}
				return false;
			}
		}
	}
}

function aac($app) {
	global $db;
	$path = THINKAPP . '/' . $app . '/';
	if (! class_exists ( $app )) {
		require_once $path . 'class.' . $app . '.php';
	}
	if (! class_exists ( $app )) {
		return false;
	}
	$obj = new $app ( $db );
	return $obj;

	unset ( $db );
}
//转义
function delzy($str){
	if (ini_set('magic_quotes_gpc')) {
		stripslashes($str);
	}else{
		return $str;
	}
}

function abslength($str)
{
    if(empty($str)){
        return 0;
    }
    if(function_exists('mb_strlen')){
        return mb_strlen($str,'utf-8');
    }
    else {
        preg_match_all("/./u", $str, $ar);
        return count($ar[0]);
    }
}

//数字转字符（科学记数法显示）
function sz2str($sz,$point=0)
{
	$sz = (string)$sz;
	$rsz = sprintf('%.'.$point.'f',$sz);
	return $rsz;
}

function curl_get_contents($url, $time = 5) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_TIMEOUT, $time);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)');
    curl_setopt($ch, CURLOPT_REFERER,_REFERER_);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    @curl_setopt($ch, CURLOPT_DNS_USE_GLOBAL_CACHE, true);
    curl_setopt($ch, CURLOPT_DNS_CACHE_TIMEOUT, 86400); // cache one day
    $content = curl_exec($ch);
//     return curl_errno($ch);
    curl_close($ch);
    return $content;
}
function curl_get_contents1($url,$furl){
	$ch=curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_REFERER,$furl);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	@curl_setopt($ch, CURLOPT_DNS_USE_GLOBAL_CACHE, true);
	curl_setopt($ch, CURLOPT_DNS_CACHE_TIMEOUT, 86400);
	$content = curl_exec($ch);
	curl_close($ch);
	return $content;
}

function curl_post_contents($url,$data){
	$da=array('jpushappkey'=>'63b6d03e9b13195bd0855571cb755dd1');
	$data=array_merge($data,$da);
	$ch=curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
	$content=curl_exec($ch);
	curl_close($ch);
	return $content;
}
function curl_post_contents1($url,$data){
	$ch=curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
	$content=curl_exec($ch);
	curl_close($ch);
	return $content;
}
function curlyb($url,$data){
    $ch=curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, 1);
//     curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Linux  2.4; rv:19.0) Gecko/20151212 Firefox/19.0');
    curl_setopt($ch, CURLOPT_TIMEOUT, 3);
//     curl_setopt($ch, CURLOPT_NOSIGNAL, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    $content=curl_exec($ch);
    $err=curl_error($ch);
    curl_close($ch);
    return $err.','.$content;
}

//前台显示email
function frontemail($email){
	$earr=explode('@',$email);
	$cemail=substr($earr[0],0,1).'***'.substr($earr[0],-2).'@'.$earr[1];
	return $cemail;
}

//百分比图片
function percentimg($percent){
	$path='pic/percent/'.$percent.'.png';
	if(!is_file($path)){
	$im=imagecreatetruecolor(100,10);
	$rr=imagecolorallocate($im,253,201,44);
	$cc=imagecolorallocate($im,245,245,245);
//	imagerectangle($im,0,0,$percent,10,$rr);
	imagefilledrectangle($im,0,0,$percent,10,$rr);
	imagefilledrectangle($im,$percent,0,100,10,$cc);
	imagepng($im,$path);
	imagedestroy($im);
	}
	$img='<img src="'.$path.'">';
	return $img;
}
function convert_stream($url,$type){
	$im=explode('.', $url);
	$surl=$im[0].'A'.$type;
	$url='/opt/xiaohuitong/sihui/vod/'.$url;
	$ex=explode('.', $url);
	$nurl=$ex[0].'A'.$type;
	exec("/usr/local/bin/ffmpeg -i ".$url." -vcodec h264 -acodec libfaac -y ".$nurl);
	if(filesize($nurl)<1024){
		$surl=$im[0].$type;
	}
	return $surl;
}
function convert_video($url){
// 	set_time_limit(0);
	$url='/opt/esl/vod/'.$url;
	$ex=explode('.', $url);
	$nurl=$ex[0].'.mov';
// 	$nurl='/opt/esl/sharevod/'.$nurl;
	if($ex[1]!='mov'){
		exec("/usr/local/bin/ffmpeg -i ".$url." -y ".$nurl);
// 		exec("/usr/local/bin/ffmpeg -i ".$url." -ab 128 -acodec libmp3lame -ac 1 -ar 22050 -r 29.97 -qscale 6 -y ".$nurl);
	}
	return $nurl;
}
function video_record(){
	exec("/usr/bin/sudo /usr/local/bin/ffmpeg -f oss -ac 1 -i /dev/dsp -acodec aac -f x11grab -s 1024x600 -i :0.0 /opt/esl/vod/6/a.mov");
	return true;
}

//获取视频时长
function getVedioTime($url){
	$vtime=exec("/usr/local/bin/ffmpeg -i ".$url." 2>&1 | grep 'Duration' | cut -d ' ' -f 4 | sed s/,//");
	$tt=explode(':',$vtime);
	if(intval($tt[2])<10){
		$tt1='0'.intval($tt[2]);
	}else{
		$tt1=intval($tt[2]);
	}
	$time=$tt[1].':'.$tt1;
	return $time;
}
function BigEndian2Int($byte_word, $signed = false) {
	$int_value = 0;
	$byte_wordlen = strlen($byte_word);
	for ($i = 0; $i < $byte_wordlen; $i++)
	{
	$int_value += ord($byte_word{$i}) * pow(256, ($byte_wordlen - 1 - $i));
	}
	if ($signed)
	{
		$sign_mask_bit = 0x80 << (8 * ($byte_wordlen - 1));
		if ($int_value & $sign_mask_bit)
		{
		$int_value = 0 - ($int_value & ($sign_mask_bit - 1));
		}
		}
		return $int_value;
	}

function getVTime($name){
	if(!file_exists($name)){
		return 5;
	}
	$flv_data_length=filesize($name);
	$fp = @fopen($name, 'rb');
	$flv_header = fread($fp, 5);
	fseek($fp, 5, SEEK_SET);
	$frame_size_data_length =BigEndian2Int(fread($fp, 4));
	$flv_header_frame_length = 9;
	if ($frame_size_data_length > $flv_header_frame_length) {
	fseek($fp, $frame_size_data_length - $flv_header_frame_length, SEEK_CUR);
	}
	$duration = 0;
	while ((ftell($fp) + 1) < $flv_data_length) {
	$this_tag_header = fread($fp, 16);
	$data_length = BigEndian2Int(substr($this_tag_header, 5, 3));
	$timestamp = BigEndian2Int(substr($this_tag_header, 8, 3));
	$next_offset = ftell($fp) - 1 + $data_length;
	if ($timestamp > $duration) {
	$duration = $timestamp;
	}
	fseek($fp, $next_offset, SEEK_SET);
	}
	fclose($fp);
	return $duration;
	}
function fn($time){
	$num = $time;
	$sec = intval($num / 1000);
	$h = intval($sec / 3600);
	$m = intval(($sec % 3600) / 60);
	$s = intval(($sec % 60 ));
	$tm = $h . ':' . $m . ':' . $s ;
	return $tm;
	}


/**
 * 二维数组的根据不同键值来排序。 第一个参数是二位数组名，第二个是依据键，第三个是升序还是降序，默认是升序
 * @param unknown $arr
 * @param unknown $keys
 * @param string $type
 * @return multitype:unknown
 */
function array_sort($arr, $keys, $type = 'asc') {
	$keysvalue = $new_array = array ();
	foreach ( $arr as $k => $v ) {
		$keysvalue [$k] = $v [$keys];
	}
	if ($type == 'asc') {
		asort ( $keysvalue );
	} else {
		arsort ( $keysvalue );
	}
	reset ( $keysvalue );
	foreach ( $keysvalue as $k => $v ) {
		$new_array [$k] = $arr [$k];
	}
	return $new_array;
}

/**
 * ThinkSAAS Notice
 * @param unknown $notice
 * @param string $button
 * @param string $url
 * @param string $isAutoGo
 */
function tsNotice($notice, $button = '点击返回', $url = 'javascript:history.back(-1);', $isAutoGo = false) {
	global $app;
	global $TS_SITE;
	global $TS_APP;
	global $site_theme;
	global $skin;
	global $TS_USER;
	global $TS_CF;
	global $runTime;

	$title = '提示：';

	include pubTemplate ( 'notice' );

	exit ();
}
function xhtalert($msg){
	echo "<script language='javascript'>alert('$msg');location.href='index.php?app=xht';</script>";
	exit();
}
function mt_alert($msg){
	echo "<script language='javascript'>alert('$msg');history.go(-1);</script>";
	exit();
}
function mt_close($msg){
	echo "<script language='javascript'>alert('$msg');window.close();</script>";
	exit();
}
function mt_location($msg){
	echo "<script language='javascript'>alert('$msg');location.href='index.php';</script>";
	exit();
}
function mtalert($msg){
	echo "<script language='javascript'>mtalert('$msg');history.go(-1);</script>";
	exit();
}

function mt_admin_zx($msg,$url){
	echo "<script language='javascript'>alert('$msg');window.location.href='$url';</script>";
	//exit();
}
function gym_alert($msg){
	echo "<script language='javascript'>alert('$msg');location.reload();</script>";
	exit();
}

/**
 * 系统消息
 * @param unknown $msg
 * @param string $button
 * @param string $url
 * @param string $isAutoGo
 */
function qiMsg($msg, $button = '点击返回>>', $url = 'javascript:history.back(-1);', $isAutoGo = false) {
	echo <<<EOT
<html>
<head>
EOT;
	if ($isAutoGo) {
		echo "<meta http-equiv=\"refresh\" content=\"2;url=$url\" />";
	}
	echo <<<EOT
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>PHP 提示</title>
<style type="text/css">
<!--
body {
font-family: Arial;
font-size: 12px;
line-height:150%;
text-align:center;
}
a{color:#555555;}
.main {
width:500px;
background-color:#FFFFFF;
font-size: 12px;
color: #666666;
margin:100px auto 0;
list-style:none;
padding:20px;
}
.main p {
line-height: 18px;
margin: 5px 20px;
font-size:14px;
}
-->
</style>
</head>
<body>
<div class="main">
<p>$msg</p>
<p><a href="$url">$button</a></p>
</div>
</body>
</html>
EOT;
	exit ();
}

/**
 * 分页函数
 * @param unknown $count
 * @param unknown $perlogs
 * @param unknown $page
 * @param unknown $url
 * @param string $suffix
 * @return string
 */
function pagination($count, $perlogs, $page, $url, $suffix = '') {
	global $TS_SITE;

	$urlset = $TS_SITE ['base'] ['site_urltype'];
	if ($urlset == 3) {
		$suffix = '.html';
	} elseif ($urlset == 7) {
		$suffix = '/';
	}

	$pnums = @ceil ( $count / $perlogs );
	$j=$page-1;
	if($j<1){
		$j=1;
	}
	$k=$page+1;
	if ($k>$pnums){
		$k=$pnums;
	}
	$re = '<ul>';
	if ($pnums<=6){
		for ($i=1;$i<=$pnums;$i++){
			if ($i == $page) {
				$re .= ' <li class="fysel">' . $i . '</li> ';
			} else {
				$re .= '<li onclick=location.href="' . $url . $i . $suffix . '">' . $i . '</li>';
			}
		}
	}else{
		if ($page<5){
			$re.='<li class="PrevFy" onclick=location.href="' . $url . $j . $suffix . '">上一页</li>';
		}else{
			$re .= '<li class="PrevFy" onclick=location.href="' . $url . '1' . $suffix . '">首页</li><li class="PrevFy" onclick=location.href="' . $url . $j . $suffix . '">上一页</li><li class="fymore">…</li>';
		}
		for($i = $page - 3; $i <= $page + 3 && $i <= $pnums; $i ++) {
			if ($i > 0) {
				if ($i == $page) {
					$re .= ' <li class="fysel">' . $i . '</li> ';
				} else {
					$re .= '<li onclick=location.href="' . $url . $i . $suffix . '">' . $i . '</li>';
				}
			}
		}
		if ($page + 3 < $pnums){
			$re .= '<li class="fymore">…</li><li class="NextFy" onclick=location.href="' . $url . $k . $suffix . '">下一页</li><li class="NextFy" onclick=location.href="' . $url . $pnums . $suffix . '">尾页</li>';
		}else{
			$re.='<li class="NextFy" onclick=location.href="' . $url . $k . $suffix . '">下一页</li>';
		}
	}
	$re.='</ul>';
	if ($pnums <= 1)
		$re = '';
	return $re;
}

function gympage($count,$perlogs,$page,$url){
	$pnums=@ceil($count/$perlogs);
// 	$out='<div class="page_main"><div class="but" onclick="gympage()">跳转</div><input class="but" type="text" id="pageindex" value="'.$page.'"><input type="hidden" id="pagenum" value="'.$pnums.'">';
	$prev=$page-1;
	if($prev<1){
		$prev=1;
	}
	$next=$page+1;
	if($next>$pnums){
		$next=$pnums;
	}
// 	$out.='<div class="next" onclick=location.href="'.$url.$next.'">></div>';
// 	$out.="<font>$page/$pnums</font>";
// 	$out.='<div class="prev" onclick=location.href="'.$url.$prev.'"><</div>';
// 	$out.='<select onchange="gymselpagesize(this)">';
// 	$gympgsz=isset($_COOKIE['gym_pagesize']) ? intval($_COOKIE['gym_pagesize']) : 20;
// 	$pgsz=array('20','30','50');
// 	foreach ($pgsz as $v){
// 		if($v==$gympgsz){
// 			$ckd='selected';
// 		}else{
// 			$ckd='';
// 		}
// 		$out.='<option value="'.$v.'" '.$ckd.'>'.$v.'</option>';
// 	}
// 	$out.='</select>';
// 	$out.='<span>共 '.$count.' 条记录&nbsp;&nbsp;每页:</span></div>';

	$out='<div class="page_main"><span>共 '.$count.' 条记录&nbsp;&nbsp;每页:</span>';
	$out.='<select onchange="gymselpagesize(this)">';
	$gympgsz=isset($_COOKIE['gym_pagesize']) ? intval($_COOKIE['gym_pagesize']) : 20;
	$pgsz=array('20','30','50');
	foreach ($pgsz as $v){
		if($v==$gympgsz){
			$ckd='selected';
		}else{
			$ckd='';
		}
		$out.='<option value="'.$v.'" '.$ckd.'>'.$v.'</option>';
	}
	$out.='</select>';
	$out.='<span class="glyphicon glyphicon-hand-left flft h" onclick=location.href="'.$url.$prev.'"></span>';
	$out.="<font>$page/$pnums</font>";
	$out.='<span class="glyphicon glyphicon-hand-right flft h" onclick=location.href="'.$url.$next.'"></span>';
	$out.='<input class="but" type="text" id="pageindex" value="'.$page.'"><input type="hidden" id="pagenum" value="'.$pnums.'"><div class="but" onclick="gympage()">跳转</div>';
	$out.='</div>';
	if($pnums<=1){
		$out='<div class="page_main"><span>共 '.$count.' 条记录</span></div>';
	}
	return $out;
}
function gymajaxpage($count,$perlogs,$page,$fun,$para=null){
	if($para!==null){
		$func=$fun.'('.$para.',';
	}else{
		$func=$fun.'(';
	}
	$pnums=@ceil($count/$perlogs);
// 	$out='<div class="page_main"><div class="but">跳转</div><input class="but" type="text" value="'.$page.'" onkeyup=gymajaxpage(this,"'.$fun.'",'.$para.')><input type="hidden" value="'.$pnums.'">';
	$prev=$page-1;
	if($prev<1){
		$prev=1;
	}
	$next=$page+1;
	if($next>$pnums){
		$next=$pnums;
	}
// 	$out.='<div class="next" onclick='.$func.$next.')>></div>';
// 	$out.="<font>$page/$pnums</font>";
// 	$out.='<div class="prev" onclick='.$func.$prev.')><</div>';
// 	$out.='<span>共 '.$count.' 条记录</span></div>';

	$out='<div class="page_main"><span>共 '.$count.' 条记录</span>';
	$out.='<span class="glyphicon glyphicon-hand-left flft h" onclick='.$func.$prev.')></span>';
	$out.="<font>$page/$pnums</font>";
	$out.='<span class="glyphicon glyphicon-hand-right flft h" onclick='.$func.$next.')></span>';
	$out.='<input class="but" type="text" value="'.$page.'" onkeyup=gymajaxpage(this,"'.$fun.'",'.$para.')><input type="hidden" value="'.$pnums.'"><div class="but">跳转</div>';
	$out.='</div>';
	if($pnums<=1){
		$out='';
	}
	return $out;
}

function AjaxPage($count, $perlogs, $page, $url, $suffix = null) {

	$pnums = @ceil ( $count / $perlogs );
	$re = '<ul>';
	$j=$page-1;
	if($j<1){
		$j=1;
	}
	$k=$page+1;
	if ($k>$pnums){
		$k=$pnums;
	}
	if ($suffix==null){
		$prev=$url.'('.$j.')';
		$next=$url.'('.$k.')';
	}else {
		$prev=$url.'('.$suffix.','.$j.')';
		$next=$url.'('.$suffix.','.$k.')';
	}
	if ($pnums<=6){
		for ($i=1;$i<=$pnums;$i++){
			if ($suffix==null){
				$urlset = $url.'('.$i.')';
			}else {
				$urlset=$url.'('.$suffix.','.$i.')';
			}
			if ($i == $page) {
				$re .= ' <li class="fysel">' . $i . '</li> ';
			} else {
				$re .= '<li onclick="' . $urlset . '">' . $i . '</li>';
			}
		}
	}else{
		if ($page<5){
			$re.='<li class="PrevFy" onclick="'.$prev.'">上一页</li>';
		}else{
			if ($suffix==''){
				$urlset = $url.'(1)';
			}else {
				$urlset=$url.'('.$suffix.',1)';
			}
			$re .= '<li class="PrevFy" onclick="' . $urlset . '">首页</li><li class="PrevFy" onclick="'.$prev.'">上一页</li><li class="fymore">…</li>';
		}
		for($i = $page - 3; $i <= $page + 3 && $i <= $pnums; $i ++) {
			if ($suffix==null){
				$urlset = $url.'('.$i.')';
				$prev=$url.'('.$j.')';
				$next=$url.'('.$k.')';
			}else {
				$urlset=$url.'('.$suffix.','.$i.')';
				$prev=$url.'('.$suffix.','.$j.')';
				$next=$url.'('.$suffix.','.$k.')';
			}
			if ($i > 0) {
				if ($i == $page) {
					$re .= ' <li class="fysel">' . $i . '</li> ';
				} else {
					$re .= '<li onclick="' . $urlset . '">' . $i . '</li>';
				}
			}
		}
		if ($page + 3 < $pnums){
			if ($suffix==''){
				$urlset = $url.'('.$pnums.')';
			}else {
				$urlset=$url.'('.$suffix.','.$pnums.')';
			}
			$re .= '<li class="fymore">…</li><li class="NextFy" onclick="'.$next.'">下一页</li><li class="NextFy" onclick="' . $urlset . '">尾页</li>';
		}else{
			$re.='<li class="NextFy" onclick="'.$next.'">下一页</li>';
		}
	}
	$re.='</ul>';
	if ($pnums <= 1)
		$re = '';
	return $re;
}

function valid_mb($mb){
	if(preg_match ( '/^1\d{10}$/', $mb )){
		return true;
	}else{
		return false;
	}
}
/**
 * 验证Email
 * @param unknown $email
 * @return boolean
 */
function valid_email($email) {
	if (preg_match ( '/^[A-Za-z0-9]+([._\-\+]*[A-Za-z0-9]+)*@([A-Za-z0-9-]+\.)+[A-Za-z0-9]+$/', $email )) {
		return true;
	} else {
		return false;
	}
}

/**
 * 处理时间的函数
 * @param unknown $btime
 * @param unknown $etime
 * @return string
 */
function getTime($btime, $etime) {
	if ($btime < $etime) {
		$stime = $btime;
		$endtime = $etime;
	} else {
		$stime = $etime;
		$endtime = $btime;
	}
	$timec = $endtime - $stime;
	$days = intval ( $timec / 86400 );
	$rtime = $timec % 86400;
	$hours = intval ( $rtime / 3600 );
	$rtime = $rtime % 3600;
	$mins = intval ( $rtime / 60 );
	$secs = $rtime % 60;
	if ($days >= 1) {
		return $days . ' 天前';
	}
	if ($hours >= 1) {
		return $hours . ' 小时前';
	}

	if ($mins >= 1) {
		return $mins . ' 分钟前';
	}
	if ($secs >= 1) {
		return $secs . ' 秒前';
	}
}

/**
 * 获取用户IP
 * @return Ambigous <string, unknown>
 */
function getIp() {
	if (getenv ( 'HTTP_CLIENT_IP' ) && strcasecmp ( getenv ( 'HTTP_CLIENT_IP' ), 'unknown' )) {
		$PHP_IP = getenv ( 'HTTP_CLIENT_IP' );
	} elseif (getenv ( 'HTTP_X_FORWARDED_FOR' ) && strcasecmp ( getenv ( 'HTTP_X_FORWARDED_FOR' ), 'unknown' )) {
		$PHP_IP = getenv ( 'HTTP_X_FORWARDED_FOR' );
	} elseif (getenv ( 'REMOTE_ADDR' ) && strcasecmp ( getenv ( 'REMOTE_ADDR' ), 'unknown' )) {
		$PHP_IP = getenv ( 'REMOTE_ADDR' );
	} elseif (isset ( $_SERVER ['REMOTE_ADDR'] ) && $_SERVER ['REMOTE_ADDR'] && strcasecmp ( $_SERVER ['REMOTE_ADDR'], 'unknown' )) {
		$PHP_IP = $_SERVER ['REMOTE_ADDR'];
	}
	preg_match ( "/[\d\.]{7,15}/", $PHP_IP, $ipmatches );
	$PHP_IP = $ipmatches [0] ? $ipmatches [0] : 'unknown';
	return $PHP_IP;
}

/**
 * 纯文本输入
 * @param unknown $text
 * @return mixed
 */
function t($text) {
	$text = preg_replace_callback ( '/\[.*?\]/is', function($m){return "";}, $text );
	$text = cleanJs ( $text );
	// 彻底过滤空格BY QINIAO
	$text = preg_replace_callback ( '/\s(?=\s)/', function($m){return "";}, $text );
	$text = preg_replace_callback ( '/[\n\r\t]/', function($m){return " ";}, $text );
	$text = str_replace ( '  ', ' ', $text );
	// $text = str_replace ( ' ', '', $text );
	$text = str_replace ( '&nbsp;', '', $text );
	$text = str_replace ( '&', '', $text );
	$text = str_replace ( '=', '', $text );
	$text = str_replace ( '-', '', $text );
	$text = str_replace ( '#', '', $text );
	$text = str_replace ( '%', '', $text );
	$text = str_replace ( '!', '', $text );
	$text = str_replace ( '@', '', $text );
	$text = str_replace ( '^', '', $text );
	$text = str_replace ( '*', '', $text );
	$text = str_replace ( 'amp;', '', $text );

	$text = str_replace ( 'position', '', $text );

	$text = strip_tags ( $text );
	$text = htmlspecialchars ( $text );
	$text = str_replace ( "'", "", $text );
	return $text;
}
//Json_Encode
function arrayRecursive(&$array, $function, $apply_to_keys_also = false)
{
	static $recursive_counter = 0;
	if (++$recursive_counter > 1000) {
		die('possible deep recursion attack');
	}
	foreach ($array as $key => $value) {
		if (is_array($value)) {
			arrayRecursive($array[$key], $function, $apply_to_keys_also);
		} else {
			$array[$key] = $function($value);
		}

		if ($apply_to_keys_also && is_string($key)) {
			$new_key = $function($key);
			if ($new_key != $key) {
				$array[$new_key] = $array[$key];
				unset($array[$key]);
			}
		}
	}
	$recursive_counter--;
}

function mttojson($arr){
	$op='[';
	foreach ($arr as $u){
		if (is_array($u)){
			if($op=='['){
				$op.='{';
			}else{
				$op.=',{';
			}
			$pi=0;
			foreach ($u as $v){
				if($pi==0){
					$op.="'".$v."'";
				}else{
					$op.=",'".$v."'";
				}
				$pi++;
			}
			$op.='}';
		}else{
			if($op=='['){
				$op.="'".$u."'";
			}else{
				$op.=",'".$u."'";
			}
		}
	}
	$op.="]";
	return $op;
}

function tojson($array) {
// 	arrayRecursive($array, 'urlencode', true);
// 	$json = json_encode($array);
// 	return urldecode($json);
//     $str=json_encode($array,JSON_UNESCAPED_UNICODE);
//     return str_replace("null", '""', $str);
//     $str = json_encode($array);
//     $str = preg_replace_callback("#\\\u([0-9a-f]{4})#i",function($matchs){
//         return iconv('UCS-2BE', 'UTF-8', pack('H4', $matchs[1]));
//     },$str);
//     return $str;
    return json_encode($array);
}
function tojson1($array){
    $str=json_encode($array,JSON_UNESCAPED_UNICODE);
    return str_replace("null", '""', $str);
}
function toArray($json){
	$json=str_replace("\\", "\\\\", $json);
	$json=str_replace("\r", "", $json);
	return json_decode($json,true);
}
function json2arr($json){
	$json=str_replace("'", '"', $json);
	return json_decode($json,true);
}

function unicode2utf8($str){
	if(!$str) return $str;
	$decode = json_decode($str);
	if($decode) return $decode;
	$str = '["' . $str . '"]';
	$decode = json_decode($str);
	if(count($decode) == 1){
		return $decode[0];
	}
	return $str;
}
function obj2arr($str){
	return json_decode(json_encode(simplexml_load_string($str,true)));
}
function unicode_encode($name)
{
    $name = iconv('UTF-8', 'UCS-2', $name);
    $len = strlen($name);
    $str = '';
    for ($i = 0; $i < $len - 1; $i = $i + 2)
    {
        $c = $name[$i];
        $c2 = $name[$i + 1];
        if (ord($c) > 0)
        {    // 两个字节的文字
            $str .= '\u'.base_convert(ord($c), 10, 16).base_convert(ord($c2), 10, 16);
        }
        else
        {
            $str .= $c2;
        }
    }
    return $str;
}
function unicode_decode($name)
{
// 转换编码，将Unicode编码转换成可以浏览的utf-8编码
	$pattern = '/([\w]+)|(\\\u([\w]{4}))/i';
	preg_match_all($pattern, $name, $matches);
	if (!empty($matches))
	{
		$name = '';
		for ($j = 0; $j < count($matches[0]); $j++)
		{
			$str = $matches[0][$j];
			if (strpos($str, '\\u') === 0)
			{
				$code = base_convert(substr($str, 2, 2), 16, 10);
				$code2 = base_convert(substr($str, 4), 16, 10);
				$c = chr($code).chr($code2);
				$c = iconv('UCS-2', 'UTF-8', $c);
				$name .= $c;
			}
			else
			{
				$name .= $str;
			}
		}
	}
	return $name;
}
function uni_encode($str){
	$str = iconv('UTF-8', 'UCS-2', $str);
	$arrstr = str_split($str, 2);
	$unistr = '';
	for($i = 0, $len = count($arrstr); $i < $len; $i++) {
		$dec = hexdec(bin2hex($arrstr[$i]));
		$unistr .='\u'. $dec;
	}
	return $unistr;
}
function uni_decode($str){
	$arruni = explode('\u', $str);
	$unistr = '';
	for($i = 1, $len = count($arruni); $i < $len; $i++) {
		$temp = intval($arruni[$i]);
		$unistr .= ($temp < 256) ? chr(0) . chr($temp) : chr($temp / 256) . chr($temp % 256);
	}
	return iconv('UCS-2', 'UTF-8', $unistr);
}
/**
 * 输入安全的html，针对存入数据库中的数据进行的过滤和转义
 * @param unknown $text
 * @return string
 */
function h($text) {
	$text = trim ( $text );
	$text = htmlspecialchars ( $text );
	$text = addslashes ( $text );
	return $text;
}

function hf($text) {
	$text = trim ( $text );
	$text = stripslashes ( $text );
	$text = htmlspecialchars_decode ( $text );
	$text = stripslashes ( $text );
	return $text;
}

/**
 * utf-8截取
 * @param unknown $string
 * @param number $start
 * @param unknown $sublen
 * @param string $append
 * @return string
 */
function cututf8($string, $start = 0, $sublen, $append = true) {
	$pa = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/";
	preg_match_all ( $pa, $string, $t_string );
	if (count ( $t_string [0] ) - $start > $sublen && $append == true) {
		return join ( '', array_slice ( $t_string [0], $start, $sublen ) ) . "...";
	} else {
		return join ( '', array_slice ( $t_string [0], $start, $sublen ) );
	}
}

/**
 * utf-8截取过渡
 * @param unknown $string
 * @param number $start
 * @param unknown $sublen
 * @param string $append
 * @return string
 */
function getsubstrutf8($string, $start = 0, $sublen, $append = true) {
	return cututf8 ( $string, $start = 0, $sublen, $append = true );
}

/**
 * 计算时间
 * @return number
 */
function getmicrotime() {
	list ( $usec, $sec ) = explode ( " ", microtime () );
	return (( float ) $usec + ( float ) $sec);
}

/**
 * 写入文件，支持Memcache缓存
 * @param unknown $file 缓存文件
 * @param unknown $dir 缓存目录
 * @param unknown $data	缓存内容
 * @param number $isphp
 * @return boolean
 */
function fileWrite($file, $dir, $data, $isphp = 1) {
	global $TS_CF, $TS_MC;

	$dfile = $dir . '/' . $file;

	// 支持memcache
	if ($TS_CF ['memcache'] && extension_loaded ( 'memcache' )) {
		$TS_MC->delete ( md5 ( $dfile ) );
		$TS_MC->set ( md5 ( $dfile ), $data, 0, 172800 );
	}

	// 同时保存文件
	! is_dir ( $dir ) ? mkdir ( $dir, 0777 ) : '';
	if (is_file ( $dfile ))
		unlink ( $dfile );
	if ($isphp == 1) {
		$data = "<?php\ndefined('IN_TS') or die('Access Denied.');\nreturn " . var_export ( $data, true ) . ";";
	}

	file_put_contents ( $dfile, $data );

	return true;
}

/**
 * 读取文件 支持Memcache缓存 $dfile 文件
 * @param unknown $dfile
 */
function fileRead($dfile) {
	global $TS_CF, $TS_MC;
	// 支持memcache
	if ($TS_CF ['memcache'] && extension_loaded ( 'memcache' )) {

		if ($TS_MC->get ( md5 ( $dfile ) )) {
			return $TS_MC->get ( md5 ( $dfile ) );
		} else {
			if (is_file ( $dfile ))
				return include $dfile;
		}
	} else {

		if (is_file ( $dfile ))
			return include $dfile;
	}
}

/**
 * 把数组转换为,号分割的字符串
 * @param unknown $arr
 * @return Ambigous <string, unknown>
 */
function array_to_str($arr) {
	$str = '';
	$count = 1;
	if (is_array ( $arr )) {
		foreach ( $arr as $a ) {
			if ($count == 1) {
				$str .= $a;
			} else {
				$str .= ',' . $a;
			}
			$count ++;
		}
	}
	return $str;
}

/**
 * 生成随机数(1数字,0字母数字组合)
 * @param unknown $length
 * @param number $numeric
 * @return string
 */
function random($length, $numeric = 0) {
	PHP_VERSION < '4.2.0' ? mt_srand ( ( double ) microtime () * 1000000 ) : mt_srand ();
	$seed = base_convert ( md5 ( print_r ( $_SERVER, 1 ) . microtime () ), 16, $numeric ? 10 : 35 );
	$seed = $numeric ? (str_replace ( '0', '', $seed ) . '012340567890') : ($seed . 'zZ' . strtoupper ( $seed ));
	$hash = '';
	$max = strlen ( $seed ) - 1;
	for($i = 0; $i < $length; $i ++) {
		$hash .= $seed [mt_rand ( 0, $max )];
	}
	return $hash;
}

/**
 * 封装一个采集函数
 * @param unknown $url	网址
 * @param unknown $proxy	代理
 * @param unknown $timeout	跳出时间
 * @return mixed
 */
function getHtmlByCurl($url, $proxy, $timeout) {
	$ch = curl_init ();
	curl_setopt ( $ch, CURLOPT_PROXY, $proxy );
	curl_setopt ( $ch, CURLOPT_URL, $url );
	curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
	curl_setopt ( $ch, CURLOPT_CONNECTTIMEOUT, $timeout );
	$file_contents = curl_exec ( $ch );
	return $file_contents;
}

/**
 * 计算文件大小
 * @param unknown $size
 * @return string
 */
function format_bytes($size) {
	$units = array (
			' B',
			' KB',
			' MB',
			' GB',
			' TB'
	);
	for($i = 0; $size >= 1024 && $i < 4; $i ++)
		$size /= 1024;
	return round ( $size, 2 ) . $units [$i];
}

/**
 * 对象转数组
 * @param unknown $array
 * @return array
 */
function object2array($array) {
	if (is_object ( $array )) {
		$array = ( array ) $array;
	}
	if (is_array ( $array )) {
		foreach ( $array as $key => $value ) {
			$array [$key] = object2array ( $value );
		}
	}
	return $array;
}

/**
 * 写文件
 *
 * @param string $file
 *        	- 需要写入的文件，系统的绝对路径加文件名
 * @param string $content
 *        	- 需要写入的内容
 * @param string $mod
 *        	- 写入模式，默认为w
 * @param boolean $exit
 *        	- 不能写入是否中断程序，默认为中断
 * @return boolean 返回是否写入成功
 *
 */
function isWriteFile($file, $content, $mod = 'w', $exit = TRUE) {
	if (! @$fp = @fopen ( $file, $mod )) {
		if ($exit) {
			exit ( 'File :<br>' . $file . '<br>Have no access to write!' );
		} else {
			return false;
		}
	} else {
		@flock ( $fp, 2 );
		@fwrite ( $fp, $content );
		@fclose ( $fp );
		return true;
	}
}

/**
 * 创建目录
 * @param unknown $dir
 * @return boolean
 */
function makedir($dir) {
	return is_dir ( $dir ) or (makedir ( dirname ( $dir ) ) and mkdir ( $dir, 0777 ));
}

/**
 * 加载模板
 * @param string $file
 *        	- 模板文件名
 * @return string 返回编译后模板的系统绝对路径
 * @param array $self
 *        	自定义路径，必须是数组格式
 *
 */
function template($file, $plugin = '', $self = '') {
	global $app;

	if ($plugin) {
		$tplfile = 'plugins/' . $app . '/' . $plugin . '/' . $file . '.html';
		if (! is_file ( $tplfile )) {
			$tplfile = 'plugins/pubs/' . $plugin . '/' . $file . '.html';
		}
		$objfile = 'cache/template/' . $plugin . '.' . $file . '.tpl.php';
	} else if ($self) {
		foreach ( $self as $v ) {
			$tplfile .= $v . '/';
			$cache = $v . '_';
		}
		$tplfile = $tplfile . $file . '.html';
		$objfile = 'cache/template/self/' . $self [3] . '.' . $file . '.tpl.php';
	} else {
		$tplfile = 'app/' . $app . '/html/' . $file . '.html';
		$objfile = 'cache/template/' . $app . '.' . $file . '.tpl.php';
	}

	if (@filemtime ( $tplfile ) > @filemtime ( $objfile )) {
		// note 加载模板类文件
		require_once 'thinksaas/tsTemplate.php';
		$T = new tsTemplate ();

		$T->complie ( $tplfile, $objfile );
	}

	return $objfile;
	unset ( $app );
}

/**
 * 加载公用html模板文件
 * @param unknown $file
 * @return string
 */
function pubTemplate($file) {
	$tplfile = 'public/html/' . $file . '.html';
	$objfile = 'cache/template/public.' . $file . '.tpl.php';

	if (@filemtime ( $tplfile ) > @filemtime ( $objfile )) {
		// note 加载模板类文件

		require_once 'thinksaas/tsTemplate.php';
		$T = new tsTemplate ();

		$T->complie ( $tplfile, $objfile );
	}

	return $objfile;
}

/**
 * 该函数在插件中调用,挂载插件函数到预留的钩子上,针对app各个的插件部分，修改自Emlog
 *
 * @param string $hook
 * @param string $actionFunc
 * @return boolearn
 *
 */
function addAction($hook, $actionFunc) {
	global $tsHooks;
	if (! @in_array ( $actionFunc, $tsHooks [$hook] )) {
		$tsHooks [$hook] [] = $actionFunc;
	}

	return true;
}

/**
 * 执行挂在钩子上的函数,支持多参数 eg:doAction('post_comment', $author, $email, $url, $comment);
 * @param string $hook
 */
function doAction($hook) {
	global $tsHooks, $TS_CF;
	$args = array_slice ( func_get_args (), 1 );
	if (isset ( $tsHooks [$hook] )) {
		foreach ( $tsHooks [$hook] as $function ) {
			$string = call_user_func_array ( $function, $args );
		}
	}

	if ($TS_CF ['hook'])
		var_dump ( $hook );
}
function createFolders($path) {
	// 递归创建
	if (! file_exists ( $path )) {
		createFolders ( dirname ( $path ) ); // 取得最后一个文件夹的全路径返回开始的地方
		mkdir ( $path, 0777 );
	}
}

/**
 * 删除文件夹和文件夹下所有的文件
 * @param string $dir
 * @return boolean
 */
function delDir($dir = '') {
	if (empty ( $dir )) {
		$dir = rtrim ( RUNTIME_PATH, '/' );
	}
	if (substr ( $dir, - 1 ) == '/') {
		$dir = rtrim ( $dir, '/' );
	}
	if (! file_exists ( $dir ))
		return true;
	if (! is_dir ( $dir ) || is_link ( $dir ))
		return @unlink ( $dir );
	foreach ( scandir ( $dir ) as $item ) {
		if ($item == '.' || $item == '..')
			continue;
		if (! delDir ( $dir . "/" . $item )) {
			@chmod ( $dir . "/" . $item, 0777 );
			if (! delDir ( $dir . "/" . $item ))
				return false;
		}
		;
	}
	return @rmdir ( $dir );
}

function mtdelfiles($dir = '') {
	if (empty ( $dir )) {
		$dir = rtrim ( RUNTIME_PATH, '/' );
	}
	if (substr ( $dir, - 1 ) == '/') {
		$dir = rtrim ( $dir, '/' );
	}
	if (! file_exists ( $dir ))
		return true;
	if (! is_dir ( $dir ) || is_link ( $dir ))
		return @unlink ( $dir );
	foreach ( scandir ( $dir ) as $item ) {
		if ($item == '.' || $item == '..')
			continue;
		if (! delDir ( $dir . "/" . $item )) {
			@chmod ( $dir . "/" . $item, 0777 );
			if (! delDir ( $dir . "/" . $item ))
				return false;
		}
		;
	}
}
/**
 * 获取带http的网站域名
 * @return string
 */
function getHttpUrl() {
	$arrUri = explode ( 'index.php', $_SERVER ['REQUEST_URI'] );
	$site_url = 'http://' . $_SERVER ['HTTP_HOST'] . $arrUri [0];
	return $site_url;
}

/**
 * 10位MD5值
 * @param string $str
 * @return string
 */
function md10($str = '') {
	return substr ( md5 ( $str ), 10, 10 );
}

/**
 * ThinkSAAS专用图片截图函数
 * @param unknown $file	数据库里的图片url
 * @param unknown $app	app名称
 * @param unknown $w	缩略图片宽度
 * @param unknown $h	缩略图片高度
 * @param string $path
 * @param string $c	1裁切,0不裁切
 * @return void|string
 */
function tsXimg($file, $app, $w, $h, $path = '', $c = '0') {
	global $TS_CF;
	if (! $file) {
		return;
	}

	$info = explode ( '.', $file );

	$name = md10 ( $file ) . '_' . $w . '_' . $h . '.' . $info [1];

	if ($path == '') {
		$cpath = 'cache/' . $app . '/' . $w . '/' . $name;
	} else {
		$cpath = 'cache/' . $app . '/' . $path . '/' . $w . '/' . $name;
	}

	if (! is_file ( $cpath )) {
		createFolders ( 'cache/' . $app . '/' . $path . '/' . $w );
		$dest = 'uploadfile/' . $app . '/' . $file;
		$arrImg = getimagesize ( $dest );
		if ($arrImg [0] <= $w) {
			copy ( $dest, $cpath );
		} else {
			require_once 'thinksaas/tsImage.php';
			$resizeimage = new tsImage ( "$dest", $w, $h, $c, "$cpath" );
		}
	}

	if ($TS_CF ['fileurl'] ['url']) {

		return 'http://' . $TS_CF ['fileurl'] ['url'] . '/' . $cpath;
	} else {

		return SITE_URL . $cpath;
	}
}

/**
 * TS专用删除缓存图片
 * @param unknown $file 数据库里的图片url
 * @param unknown $app app名称
 * @param unknown $w 缩略图片宽度
 * @param unknown $h 缩略图片高度
 * @param unknown $path
 * @return boolean
 */
function tsDimg($file, $app, $w, $h, $path) {
	$info = explode ( '.', $file );
	$name = md10 ( $file ) . '_' . $w . '_' . $h . '.' . $info [1];
	unlink ( 'cache/' . $app . '/' . $path . '/' . $w . '/' . $name );
	return true;
}

/**
 * gzip压缩输出
 * @param unknown $content
 * @return string
 */
function ob_gzip($content) {
	if (! headers_sent () && extension_loaded ( "zlib" ) && strstr ( $_SERVER ["HTTP_ACCEPT_ENCODING"], "gzip" )) {
		// $content = gzencode($content." \n//此页已压缩",9);
		$content = gzencode ( $content, 9 );
		header ( "Content-Encoding: gzip" );
		header ( "Vary: Accept-Encoding" );
		header ( "Content-Length: " . strlen ( $content ) );
	}
	return $content;
}

/**
 * tsUrl提供至少4种的url展示方式
 * (1)index.php?app=group&ac=topic&topicid=1 //标准默认模式
 * (2)index.php/group/topic/topicid-1 //path_info模式
 * (3)group-topic-topicid-1.html //rewrite模式1
 * (4)group/topic/topicid-1 //rewrite模式2
 * @param unknown $app
 * @param string $ac
 * @param unknown $params
 * @return string
 */
function tsUrl($app, $ac = '', $params = array()) {
	global $TS_CF;
	global $TS_SITE;
	$urlset = $TS_SITE ['base'] ['site_urltype'];

	if ($urlset == 1) {
		foreach ( $params as $k => $v ) {
			$str .= '&' . $k . '=' . $v;
		}
		if ($ac == '') {
			$ac = '';
		} else {
			if ($TS_CF ['subdomain'] && in_array ( $app, $TS_CF ['subdomain'] ['app'] ) || $TS_CF ['appdomain'] [$app]) {
				$ac = '?ac=' . $ac;
			} else {
				$ac = '&ac=' . $ac;
			}
		}
		if ($TS_CF ['subdomain'] && in_array ( $app, $TS_CF ['subdomain'] ['app'] ) || $TS_CF ['appdomain'] [$app]) {
			$url = 'index.php' . $ac . $str;
		} else {
			$url = 'index.php?app=' . $app . $ac . $str;
		}
	} elseif ($urlset == 2) {
		foreach ( $params as $k => $v ) {
			$str .= '/' . $k . '-' . $v;
		}
		if ($ac == '') {
			$ac = '';
		} else {
			$ac = '/' . $ac;
		}

		if ($TS_CF ['subdomain'] && in_array ( $app, $TS_CF ['subdomain'] ['app'] ) || $TS_CF ['appdomain'] [$app]) {
			$url = 'index.php' . $ac . $str;
		} else {
			$url = 'index.php/' . $app . $ac . $str;
		}
	} elseif ($urlset == 3) {
		foreach ( $params as $k => $v ) {
			$str .= '-' . $k . '-' . $v;
		}

		if ($ac == '') {
			$ac = '';
		} else {
			if ($TS_CF ['subdomain'] && in_array ( $app, $TS_CF ['subdomain'] ['app'] ) || $TS_CF ['appdomain'] [$app]) {
				$ac = $ac;
			} else {
				$ac = '-' . $ac;
			}
		}

		$page = strpos ( $str, 'page' );

		if ($page) {
			if ($TS_CF ['subdomain'] && in_array ( $app, $TS_CF ['subdomain'] ['app'] ) || $TS_CF ['appdomain'] [$app]) {
				$url = $ac . $str;
			} else {
				$url = $app . $ac . $str;
			}
		} else {
			if ($TS_CF ['subdomain'] && in_array ( $app, $TS_CF ['subdomain'] ['app'] ) || $TS_CF ['appdomain'] [$app]) {
				$url = $ac . $str . '.html';
			} else {
				$url = $app . $ac . $str . '.html';
			}
		}
	} elseif ($urlset == 4) {
		foreach ( $params as $k => $v ) {
			$str .= '/' . $k . '-' . $v;
		}
		if ($ac == '') {
			$ac = '';
		} else {
			if ($TS_CF ['subdomain'] && in_array ( $app, $TS_CF ['subdomain'] ['app'] ) || $TS_CF ['appdomain'] [$app]) {
				$ac = $ac;
			} else {
				$ac = '/' . $ac;
			}
		}
		if ($TS_CF ['subdomain'] && in_array ( $app, $TS_CF ['subdomain'] ['app'] ) || $TS_CF ['appdomain'] [$app]) {
			$url = $ac . $str;
		} else {
			$url = $app . $ac . $str;
		}
	} elseif ($urlset == 5) {
		foreach ( $params as $k => $v ) {
			$str .= '/' . $k . '/' . $v;
		}
		$str = str_replace ( '/id', '', $str );
		if ($ac == '') {
			$ac = '';
		} else {
			if ($TS_CF ['subdomain'] && in_array ( $app, $TS_CF ['subdomain'] ['app'] ) || $TS_CF ['appdomain'] [$app]) {
				$ac = $ac;
			} else {
				$ac = '/' . $ac;
			}
		}
		if ($TS_CF ['subdomain'] && in_array ( $app, $TS_CF ['subdomain'] ['app'] ) || $TS_CF ['appdomain'] [$app]) {
			$url = $ac . $str;
		} else {
			$url = $app . $ac . $str;
		}
	} elseif ($urlset == 6) {
		foreach ( $params as $k => $v ) {
			$str .= '/' . $k . '/' . $v;
		}

		if ($ac == '') {
			$ac = '';
		} else {
			if ($TS_CF ['subdomain'] && in_array ( $app, $TS_CF ['subdomain'] ['app'] ) || $TS_CF ['appdomain'] [$app]) {
				$ac = $ac;
			} else {
				$ac = '/' . $ac;
			}
		}
		if ($TS_CF ['subdomain'] && in_array ( $app, $TS_CF ['subdomain'] ['app'] ) || $TS_CF ['appdomain'] [$app]) {
			$url = $ac . $str;
		} else {
			$url = $app . $ac . $str;
		}
	} elseif ($urlset == 7) {
		foreach ( $params as $k => $v ) {
			$str .= '/' . $k . '/' . $v;
		}
		$str = str_replace ( '/id', '', $str );
		if ($ac == '') {
			$ac = '';
		} else {
			if ($TS_CF ['subdomain'] && in_array ( $app, $TS_CF ['subdomain'] ['app'] ) || $TS_CF ['appdomain'] [$app]) {
				$ac = $ac;
			} else {
				$ac = '/' . $ac;
			}
		}

		$page = strpos ( $str, 'page' );

		if ($page) {
			if ($TS_CF ['subdomain'] && in_array ( $app, $TS_CF ['subdomain'] ['app'] ) || $TS_CF ['appdomain'] [$app]) {
				$url = $ac . $str;
			} else {
				$url = $app . $ac . $str;
			}
		} else {
			if ($TS_CF ['subdomain'] && in_array ( $app, $TS_CF ['subdomain'] ['app'] ) || $TS_CF ['appdomain'] [$app]) {
				if ($ac == '') {
					$url = '';
				} else {
					$url = $ac . $str . '/';
				}
			} else {
				$url = $app . $ac . $str . '/';
			}
		}
	}
	if ($TS_CF ['subdomain'] && in_array ( $app, $TS_CF ['subdomain'] ['app'] )) {
		return 'http://' . $app . '.' . $TS_CF ['subdomain'] ['domain'] . '/' . $url;
	} elseif ($TS_CF ['appdomain'] [$app]) {
		return 'http://' . $TS_CF ['appdomain'] [$app] . '/' . $url;
	} else {
		return SITE_URL . $url;
	}
}

/**
 * reurl
 */
function reurl() {
	global $tsMySqlCache;
	$options = fileRead ( 'data/system_options.php' );

	if ($options == '') {
		$options = $tsMySqlCache->get ( 'system_options' );
	}

	$scriptName = explode ( 'index.php', $_SERVER ['SCRIPT_NAME'] );
	$rurl = substr ( $_SERVER ['REQUEST_URI'], strlen ( $scriptName [0] ) );

	// 针对QQ开放平台做一下修改strpos($rurl,'?openid=')==true
	if (strpos ( $rurl, '?' ) == false || strpos ( $rurl, '?openid=' ) == true) {

		if (preg_match ( '/index.php/i', $rurl )) {
			$rurl = str_replace ( 'index.php', '', $rurl );
			$rurl = substr ( $rurl, 1 );
			$params = $rurl;
		} else {
			$params = $rurl;
		}

		if ($rurl) {

			if ($options ['site_urltype'] == 3) {
				// http://localhost/group-topic-id-1.html
				$params = explode ( '.', $params );

				$params = explode ( '-', $params [0] );

				foreach ( $params as $p => $v ) {
					switch ($p) {
						case 0 :
							$_GET ['app'] = $v;
							break;
						case 1 :
							$_GET ['ac'] = $v;
							break;
						default :

							if ($v)
								$kv [] = $v;

							break;
					}
				}

				$ck = count ( $kv ) / 2;

				if ($ck >= 2) {
					$arrKv = array_chunk ( $kv, $ck );
					foreach ( $arrKv as $key => $item ) {
						$_GET [$item [0]] = $item [1];
					}
				} elseif ($ck == 1) {
					$_GET [$kv [0]] = $kv [1];
				} else {
				}
			} elseif ($options ['site_urltype'] == 4) {
				// http://localhost/group/topic/id-1
				$params = explode ( '/', $params );

				foreach ( $params as $p => $v ) {
					switch ($p) {
						case 0 :
							$_GET ['app'] = $v;
							break;
						case 1 :
							$_GET ['ac'] = $v;
							break;
						default :
							$kv = explode ( '-', $v );

							if (count ( $kv ) > 1) {
								$_GET [$kv [0]] = $kv [1];
							} else {
								$_GET ['params' . $p] = $kv [0];
							}
							break;
					}
				}
			} elseif ($options ['site_urltype'] == 5) {
				// http://localhost/group/topic/1
				$params = explode ( '/', $params );

				foreach ( $params as $p => $v ) {
					switch ($p) {
						case 0 :
							$_GET ['app'] = $v;
							break;
						case 1 :
							$_GET ['ac'] = $v;
							if (empty ( $_GET ['ac'] ))
								$_GET ['ac'] = 'index';
							break;
						case 2 :
							if ((( int ) $v) > 0) {
								$_GET ['id'] = $v;
								break;
							}
							// 处理TAG
							if ($_GET ['ac'] == 'tag') {
								$_GET ['id'] = $v;
								break;
							}

						default :
							$_GET [$v] = $params [$p + 1];
							break;
					}
				}
			} elseif ($options ['site_urltype'] == 6) {
				// http://localhost/group/topic/id/1
				$params = explode ( '/', $params );

				foreach ( $params as $p => $v ) {
					switch ($p) {
						case 0 :
							$_GET ['app'] = $v;
							break;
						case 1 :
							$_GET ['ac'] = $v;
							break;
						default :
							$_GET [$v] = $params [$p + 1];
							break;
					}
				}
			} elseif ($options ['site_urltype'] == 7) {
				// http://localhost/group/topic/1/
				$params = explode ( '/', $params );

				foreach ( $params as $p => $v ) {
					switch ($p) {
						case 0 :
							$_GET ['app'] = $v;
							break;
						case 1 :
							$_GET ['ac'] = $v;
							if (empty ( $_GET ['ac'] ))
								$_GET ['ac'] = 'index';
							break;
						case 2 :
							if ((( int ) $v) > 0) {
								$_GET ['id'] = $v;
								break;
							}
							// 处理TAG
							if ($_GET ['ac'] == 'tag') {
								$_GET ['id'] = $v;
								break;
							}

						default :
							$_GET [$v] = $params [$p + 1];
							break;
					}
				}
			} else {

				$params = explode ( '/', $params );

				foreach ( $params as $p => $v ) {
					switch ($p) {
						case 0 :
							$_GET ['app'] = $v;
							break;
						case 1 :
							$_GET ['ac'] = $v;
							break;

							// 处理TAG
							if ($_GET ['ac'] == 'tag') {
								$_GET ['id'] = $v;
								break;
							}

						default :
							$kv = explode ( '-', $v );
							if (count ( $kv ) > 1) {
								$_GET [$kv [0]] = $kv [1];
							} else {
								$_GET ['params' . $p] = $kv [0];
							}

							break;
					}
				}
			}
		}
	}
}

/**
 * 辅助APP二级域名
 */
function reurlsubdomain() {
	global $tsMySqlCache;
	$options = fileRead ( 'data/system_options.php' );
	if ($options == '') {
		$options = $tsMySqlCache->get ( 'system_options' );
	}

	$scriptName = explode ( 'index.php', $_SERVER ['SCRIPT_NAME'] );
	$rurl = substr ( $_SERVER ['REQUEST_URI'], strlen ( $scriptName [0] ) );

	if (strpos ( $rurl, '?' ) == false) {

		if (preg_match ( '/index.php/i', $rurl )) {
			$rurl = str_replace ( 'index.php', '', $rurl );
			$rurl = substr ( $rurl, 1 );
			$params = $rurl;
		} else {
			$params = $rurl;
		}

		if ($rurl) {

			if ($options ['site_urltype'] == 3) {
				// http://group.thinksaas.cn/topic-id-1.html
				$params = explode ( '.', $params );

				$params = explode ( '-', $params [0] );

				foreach ( $params as $p => $v ) {
					switch ($p) {
						case 0 :
							$_GET ['ac'] = $v;
							break;
						default :

							if ($v)
								$kv [] = $v;

							break;
					}
				}

				$ck = count ( $kv ) / 2;

				if ($ck >= 2) {
					$arrKv = array_chunk ( $kv, $ck );
					foreach ( $arrKv as $key => $item ) {
						$_GET [$item [0]] = $item [1];
					}
				} elseif ($ck == 1) {
					$_GET [$kv [0]] = $kv [1];
				} else {
				}
			} elseif ($options ['site_urltype'] == 4) {
				// http://group.thinksaas.cn/topic/id-1
				$params = explode ( '/', $params );

				foreach ( $params as $p => $v ) {
					switch ($p) {
						case 0 :
							$_GET ['ac'] = $v;
							break;
						default :
							$kv = explode ( '-', $v );

							if (count ( $kv ) > 1) {
								$_GET [$kv [0]] = $kv [1];
							} else {
								$_GET ['params' . $p] = $kv [0];
							}
							break;
					}
				}
			} elseif ($options ['site_urltype'] == 5) {
				// http://group.thinksaas.cn/topic/1
				$params = explode ( '/', $params );

				foreach ( $params as $p => $v ) {
					switch ($p) {
						case 0 :
							$_GET ['ac'] = $v;
							if (empty ( $_GET ['ac'] ))
								$_GET ['ac'] = 'index';
							break;
						case 1 :
							if ((( int ) $v) > 0) {
								$_GET ['id'] = $v;
								break;
							}
						default :
							$_GET [$v] = $params [$p + 1];
							break;
					}
				}
			} elseif ($options ['site_urltype'] == 6) {
				// http://group.thinksaas.cn/topic/id/1
				$params = explode ( '/', $params );

				foreach ( $params as $p => $v ) {
					switch ($p) {
						case 0 :
							$_GET ['ac'] = $v;
							break;
						default :
							$_GET [$v] = $params [$p + 1];
							break;
					}
				}
			} elseif ($options ['site_urltype'] == 7) {
				// http://group.thinksaas.cn/topic/1/
				$params = explode ( '/', $params );

				foreach ( $params as $p => $v ) {
					switch ($p) {
						case 0 :
							$_GET ['ac'] = $v;
							if (empty ( $_GET ['ac'] ))
								$_GET ['ac'] = 'index';
							break;
						case 1 :
							if ((( int ) $v) > 0) {
								$_GET ['id'] = $v;
								break;
							}
						default :
							$_GET [$v] = $params [$p + 1];
							break;
					}
				}
			} else {

				$params = explode ( '/', $params );

				foreach ( $params as $p => $v ) {
					switch ($p) {
						case 0 :
							$_GET ['ac'] = $v;
							break;
						default :
							$kv = explode ( '-', $v );
							if (count ( $kv ) > 1) {
								$_GET [$kv [0]] = $kv [1];
							} else {
								$_GET ['params' . $p] = $kv [0];
							}
							break;
					}
				}
			}
		}
	}
}

/**
 * 检测目录是否可写1可写，0不可写
 * @param unknown $file
 * @return number
 */
function iswriteable($file) {
	if (is_dir ( $file )) {
		$dir = $file;
		if ($fp = fopen ( "$dir/test.txt", 'w' )) {
			fclose ( $fp );
			unlink ( "$dir/test.txt" );
			$writeable = 1;
		} else {
			$writeable = 0;
		}
	} else {
		if ($fp = fopen ( $file, 'a+' )) {
			fclose ( $fp );
			$writeable = 1;
		} else {
			$writeable = 0;
		}
	}
	return $writeable;
}

/**
 * 删除目录下文件
 * @param unknown $dir
 */
function delDirFile($dir) {
	$arrFiles = dirList ( $dir, 'files' );
	foreach ( $arrFiles as $item ) {
		unlink ( $dir . '/' . $item );
	}
}

function uploadflv($files,$projectid,$dir,$uptypes){
	if($files['size']>0){
		$menu2 = intval ( $projectid / 1000 );

		$menu1 = intval ( $menu2 / 1000 );

		$path = $menu1 . '/' . $menu2;
		$dest_dir = 'flvupload/' . $dir . '/' . $path;
		createFolders ( $dest_dir );
		$arrType = explode ( '.', strtolower ( $files ['name'] ) ); // 转小写一下

		$type = array_pop ( $arrType );

		if (in_array ( $type, $uptypes )) {

			$name = $projectid .time() . '.' . $type;

			$dest = $dest_dir . '/' . $name;

			// 先删除
			unlink ( $dest );
			// 后上传
			move_uploaded_file ( $files ['tmp_name'], mb_convert_encoding ( $dest, "gb2312", "UTF-8" ) );

			chmod ( $dest, 0777 );

			$filesize = filesize ( $dest );
			if (intval ( $filesize ) > 0) {
				return array (
						'fname' => tsFilter($files ['name']),
						'name' => $name,
						'url' => $dest,
						'type' => $type,
						'size' => $files ['size']
				);
			} else {
				return false;
			}
		} else {
			return false;
		}
	}
}
//等比例图片压缩
function resizeimg($file,$w,$h){
	@ini_set('memory_limit','120M');
	$tp=pathinfo($file);
	$dir='pic/pic/'.$tp['filename'].'.'.$tp['extension'];
	if($tp['extension']=='jpg'){
		$img=imagecreatefromjpeg($file);
	}elseif($tp['extension']=='gif'){
		$img=imagecreatefromgif($file);
	}elseif($tp['extension']=='png'){
		$img=imagecreatefrompng($file);
	}else{
		return $file;
	}
	$imgwh=getimagesize($file);
	$img_w=$imgwh[0];
	$img_h=$imgwh[1];
	if($img_w>$w && $img_h>$h){
		$rw=$w;
		$rh=intval($img_h*$w/$img_w);
		if($rh<$h){
			$rh=$h;
			$rw=intval($img_w*$h/$img_h);
		}
	}else{
		return $file;
	}
	$tmp=imagecreatetruecolor($rw,$rh);
	imagecopyresampled($tmp,$img,0,0,0,0,$rw,$rh,$img_w,$img_h);
	if($tp['extension']=='jpg'){
		imagejpeg($tmp,$dir);
	}elseif($tp['extension']=='gif'){
		imagegif($tmp,$dir);
	}elseif($tp['extension']=='png'){
		imagepng($tmp,$dir);
	}
	imagedestroy($img);
	imagedestroy($tmp);
	return $dir;
}
function uploadpic($files,$projectid,$dir,$uptypes = array('jpg','png','gif')){
/*	if ($files['error']>0){
		return array(
			'error'=>$files['error']
		);
	//	return false;
		exit;
	}*/
	if($files['size']>0){
		$dest_dir = $dir;
		createFolders ( $dest_dir );
		$arrType = explode ( '.', strtolower ( $files ['name'] ) ); // 转小写一下
// 		return $files['size'];
		$type = array_pop ( $arrType );

		if (in_array ( $type, $uptypes )) {
			$name = $projectid .time() . '.' . $type;

			$dest = $dest_dir . '/' . $name;
			$surl=$projectid.'/'.$name;
			// 先删除
			unlink ( $dest );
			// 后上传
			move_uploaded_file ( $files ['tmp_name'], mb_convert_encoding ( $dest, "gb2312", "UTF-8" ) );
			chmod ( $dest, 0777 );

			$filesize = filesize ( $dest );
			if (intval ( $filesize ) > 0) {
				return array (
				//		'error'=>$files['error'],
						'fname' => tsFilter($files ['name']),
						'name' => $name,
						'url' => $dest,
						'surl'=>$surl,
						'type' => $type,
						'size' => $files ['size']
				);
			} else {
				return false;
			}
		} else {
			return false;
		}
	}
}

/**
 * ThinkSAAS专用上传函数
 * @param unknown $files	要上传的文件 如$_FILES['photo']
 * @param unknown $projectid	上传针对的项目id 如$userid
 * @param unknown $dir	上传到目录 如 user
 * @param unknown $uptypes	上传类型，数组 array('jpg','png','gif')
 * @return multitype:string unknown mixed |boolean	返回数组：array('name'=>'','path'=>'','url'=>'','path'=>'','size'=>'')
 */
function tsUpload($files, $projectid, $dir, $uptypes) {
	if ($files ['size'] > 0) {

		$menu2 = intval ( $projectid / 1000 );

		$menu1 = intval ( $menu2 / 1000 );

		$path = $menu1 . '/' . $menu2;

		$dest_dir = 'uploadfile/' . $dir . '/' . $path;

		createFolders ( $dest_dir );

		//$ext = pathinfo($files['name'],PATHINFO_EXTENSION);

		$arrType = explode ( '.', strtolower ( $files ['name'] ) ); // 转小写一下

		$type = array_pop ( $arrType );

		if (in_array ( $type, $uptypes )) {

			$name = $projectid . '.' . $type;

			$dest = $dest_dir . '/' . $name;

			// 先删除
			unlink ( $dest );
			// 后上传
			move_uploaded_file ( $files ['tmp_name'], mb_convert_encoding ( $dest, "gb2312", "UTF-8" ) );

			chmod ( $dest, 0777 );

			$filesize = filesize ( $dest );
			if (intval ( $filesize ) > 0) {
				return array (
						'name' => tsFilter($files ['name']),
						'path' => $path,
						'url' => $path . '/' . $name,
						'type' => $type,
						'size' => $files ['size']
				);
			} else {
				return false;
			}
		} else {
			return false;
		}
	}
}

/**
 * 扫描目录
 * @param unknown $dir
 * @param string $isDir
 * @return mixed
 */
function tsScanDir($dir, $isDir = null) {
	if ($isDir == null) {
		$dirs = array_filter ( glob ( $dir . '/' . '*' ), 'is_dir' );
	} else {
		$dirs = array_filter ( glob ( $dir . '/' . '*' ), 'is_file' );
	}

	foreach ( $dirs as $key => $item ) {
		$y = explode ( '/', $item );
		$arrDirs [] = array_pop ( $y );
	}

	return $arrDirs;
}

/**
 * 删除目录下所有文件
 * @param unknown $dir
 */
function rmrf($dir) {
	foreach ( glob ( $dir ) as $file ) {
		if (is_dir ( $file )) {
			rmrf ( "$file/*" );
			rmdir ( $file );
		} else {
			unlink ( $file );
		}
	}
}

/**
 * 内容url解析
 * @param unknown $content
 * @return mixed
 */
function urlcontent($content) {
	$pattern = '/(http:\/\/|https:\/\/|ftp:\/\/)([\w:\/\.\?=&-_#]+)/is';
	$content = preg_replace_callback ( $pattern, function($matches){return '<a rel="nofollow" target="_blank" href="'.$matches[1].$matches[2].'">'.$matches[1].$matches[2].'</a>';}, $content );
	return $content;
}

/**
 * 反序列化为UTF-8
 * @param unknown $serial_str
 * @return mixed
 */
function mb_unserialize($serial_str) {
	$serial_str = preg_replace_callback ( '!s:(\d+):"(.*?)";!se', function($matches){return 's:'.strlen($matches[2]).':'.'"'.$matches[2].'"';}, $serial_str );
	$serial_str = str_replace ( "\r", "", $serial_str );
	return unserialize ( $serial_str );
}

/**
 * 反序列化为ASC
 * @param unknown $serial_str
 * @return mixed
 */
function asc_unserialize($serial_str) {
	$serial_str = preg_replace_callback ( '!s:(\d+):"(.*?)";!se', function($matches){return 's:'.strlen($matches[2]).':'.'"'.$matches[2].'"';}, $serial_str );
	$serial_str = str_replace ( "\r", "", $serial_str );
	return unserialize ( $serial_str );
}

function ximg($projectid,$dir,$type,$str){
	$dest_dir = $dir;
	createFolders ( $dest_dir );
		$name = $projectid.time() . '.' . $type; // 要生成的图片名字

		$dest = $dest_dir . '/' . $name;
		unlink ( $dest );

		$jpg = $str; // 得到post过来的二进制原始数据
		$file = fopen ( $dest, "w" ); // 打开文件准备写入
		fwrite ( $file, $jpg ); // 写入
		fclose ( $file ); // 关闭

		chmod ( $dest, 0777 );
	return $dest;
}

function mtximg($projectid,$dir,$type,$str){
	$dest_dir = $dir;
	createFolders ( $dest_dir );

	$arr=json_decode($str,true);
	$ty=json_decode($type,true);
	foreach ($arr as $k=>$v){
	$name = $projectid.$k.time() . '.' . $ty[$k]; // 要生成的图片名字

	$dest = $dest_dir . '/' . $name;
	unlink ( $dest );

	$jpg = $v; // 得到post过来的二进制原始数据
	$file = fopen ( $dest, "w" ); // 打开文件准备写入
	fwrite ( $file, $jpg ); // 写入
	fclose ( $file ); // 关闭

	chmod ( $dest, 0777 );
	$a[]=$dest;
	}
	return $a;
}
/**
 * 二进制上传
 * @param unknown $projectid
 * @param unknown $dir
 * @param unknown $type
 * @return multitype:string unknown
 */
function mtXupload($projectid, $dir, $type) {

	$dest_dir = $dir;
	createFolders ( $dest_dir );

	$name = $projectid.time() . '.' . $type; // 要生成的图片名字

	$dest = $dest_dir . '/' . $name;
	$surl=$projectid.'/'.$name;
	// 先删除
	unlink ( $dest );

	$xmlstr = $GLOBALS [HTTP_RAW_POST_DATA];
	if (empty ( $xmlstr ))
		$xmlstr = file_get_contents ( 'php://input' );
	if (!empty($xmlstr)){
	$jpg = $xmlstr; // 得到post过来的二进制原始数据
	$file = fopen ( $dest, "w" ); // 打开文件准备写入
	fwrite ( $file, $jpg ); // 写入
	fclose ( $file ); // 关闭

	chmod ( $dest, 0777 );

	return array (
			'name' => $name,
			'path' => $dest_dir,
			'url' => $dest,
			'surl'=>$surl,
			'type' => $typ,
			'str'=>$jpg
	);
	}else{
		return false;
	}
}

function tsXupload($projectid, $dir, $type) {
	$menu2 = intval ( $projectid / 1000 );
	$menu1 = intval ( $menu2 / 1000 );
	$path = $menu1 . '/' . $menu2;
	$dest_dir = 'uploadfile/' . $dir . '/' . $path;
	createFolders ( $dest_dir );

	$name = $projectid . '.' . $type; // 要生成的图片名字

	$dest = $dest_dir . '/' . $name;

	// 先删除
	unlink ( $dest );

	$xmlstr = $GLOBALS [HTTP_RAW_POST_DATA];
	if (empty ( $xmlstr ))
		$xmlstr = file_get_contents ( 'php://input' );
	$jpg = $xmlstr; // 得到post过来的二进制原始数据
	$file = fopen ( $dest, "w" ); // 打开文件准备写入
	fwrite ( $file, $jpg ); // 写入
	fclose ( $file ); // 关闭

	chmod ( $dest, 0777 );

	return array (
			'name' => $name,
			'path' => $path,
			'url' => $path . '/' . $name,
			'type' => $type
	);
}

/**
 * 记录日志
 * @param unknown $file
 * @param unknown $data
 */
function logging($file, $data) {
	! is_dir ( 'logs' ) ? mkdir ( 'logs', 0777 ) : '';
	$dfile = 'logs/' . $file;

	$filesize = abs ( filesize ( $dfile ) );

	// 文件重命名
	if ($filesize > 1024000) {
		rename ( $dfile, $dfile . date ( 'His' ) );
	}

	$fd = fopen ( $dfile, "a+" );
	fputs ( $fd, $data );
	fclose ( $fd );
}

/**
 * 记录用户日志
 * @param unknown $array
 * @param unknown $userid
 */
function userlog(&$array, $userid) {
	if (is_array ( $array )) {
		foreach ( $array as $key => $value ) {
			if (! is_array ( $value )) {
				$data = "UserId:" . $userid . "\n";
				$data .= "IP:" . getIp () . "\n";
				$data .= "TIME:" . date ( 'Y-m-d H:i:s' ) . "\n";
				$data .= "URL:" . $_SERVER ['REQUEST_URI'] . "\n";
				$data .= "DATA:" . $data . "\n";
				$data .= "--------------------------------------\n";
				logging ( date ( 'Ymd' ) . '-' . $userid . '.txt', $data );
			} else {
				userlog ( $array [$key] );
			}
		}
	}
}

/**
 * 过滤脚本代码
 * @param unknown $text
 * @return mixed
 */
function cleanJs($text) {
	$text = trim ( $text );
	$text = stripslashes ( $text );
	// 完全过滤注释
	$text = preg_replace_callback ( '/<!--?.*-->/', function($m){return "";}, $text );
	// 完全过滤动态代码
	$text = preg_replace_callback ( '/<\?|\?>/', function($m){return "";}, $text );
	// 完全过滤js
	$text = preg_replace_callback ( '/<script?.*\/script>/', function($m){return "";}, $text );
	// 过滤多余html
	$text = preg_replace_callback ( '/<\/?(html|head|meta|link|base|body|title|style|script|form|iframe|frame|frameset)[^><]*>/i', function($m){return "";}, $text );
	// 过滤on事件lang js
	while ( preg_match ( '/(<[^><]+)(lang|data|onfinish|onmouse|onexit|onerror|onclick|onkey|onload|onchange|onfocus|onblur)[^><]+/i', $text, $mat ) ) {
		$text = str_replace ( $mat [0], $mat [1], $text );
	}
	while ( preg_match ( '/(<[^><]+)(window\.|javascript:|js:|about:|file:|document\.|vbs:|cookie)([^><]*)/i', $text, $mat ) ) {
		$text = str_replace ( $mat [0], $mat [1] . $mat [3], $text );
	}
	return $text;
}

/**
 * 输入安全过滤
 * @param unknown $text
 * @return mixed
 */
function tsClean($text) {
	$text = cleanJs ( $text );
	return $text;
}

/**
 * 统计字符长度
 * @param unknown $str
 * @return number
 */
function count_string_len($str) {
	// return (strlen($str)+mb_strlen($str,'utf-8'))/2; //开启了php_mbstring.dll扩展
	$name_len = strlen ( $str );
	$temp_len = 0;
	for($i = 0; $i < $name_len;) {
		if (strpos ( 'abcdefghijklmnopqrstvuwxyz0123456789', $str [$i] ) === false) {
			$i = $i + 3;
			$temp_len += 2;
		} else {
			$i = $i + 1;
			$temp_len += 1;
		}
	}
	return $temp_len;
}

/**
 * 针对特殊字符或者内容的特殊过滤
 * @param unknown $value
 * @return Ambigous <string, mixed>
 */
function tsFilter($value){
	$value = trim($value);
	//定义不允许提交的SQl命令和关键字
	$words = array();
	$words[] = "add ";
	$words[] = "and ";
	$words[] = "count ";
	$words[] = "order ";
	$words[] = "table ";
	$words[] = "by ";
	$words[] = "create ";
	$words[] = "delete ";
	$words[] = "drop ";
	$words[] = "from ";
	$words[] = "grant ";
	$words[] = "insert ";
	$words[] = "select ";
	$words[] = "truncate ";
	$words[] = "update ";
	$words[] = "use ";
	$words[] = "--";
	$words[] = "#";
	$words[] = "group_concat";
	$words[] = "column_name";
	$words[] = "information_schema.columns";
	$words[] = "table_schema";
	$words[] = "union ";
	$words[] = "where ";
	$words[] = "alert";
	$value = strtolower($value);//转换为小写
	foreach($words as $word){
		if(strstr($value,$word)){
			$value = str_replace($word,'',$value);
		}
	}

	return $value;
}


function tsgpc(&$array) {
	//如果是数组，遍历数组，递归调用
	if (is_array ( $array )) {
		foreach ( $array as $k => $v ) {
			$array [$k] = tsgpc ( $v );
		}
	} else if (is_string ( $array )) {
		//使用addslashes函数来处理
		$array = addslashes ( closetags($array) );
	} else if (is_numeric ( $array )) {
		$array = intval ( $array );
	}
	return $array;
}
function rn($str){
	return str_replace('<br>', '\n', $str);
}
function rh($str){
	return str_replace('<br>', chr(13), $str);
}
function rm($str){
//     $str=str_replace('\\&quot;', '\\\"', $str);
    $str=str_replace('&quot;', '"', $str);
	return str_replace("\'", "'", $str);
}
function rq($str){
    $str=str_replace("&quot;", "", $str);
    return str_replace('"', '', $str);
}
/**
 * 检查标签是否闭合
 */
function closetags($html) {
    preg_match_all('#<(?!meta|img|br|hr|input\b)\b([a-z]+)(?: .*)?(?<![/|/ ])>#iU', $html, $result);
    $openedtags = $result[1];
    preg_match_all('#</([a-z]+)>#iU', $html, $result);
    $closedtags = $result[1];
    $len_opened = count($openedtags);
    $len_closed = count($closedtags);
    if ($len_closed == $len_opened) {
        return $html;
    }
    $openedtags = array_reverse($openedtags);
    for ($i=0; $i < $len_opened; $i++) {
        if (!in_array($openedtags[$i], $closedtags)) {
            $html .= '</'.$openedtags[$i].'>';
        } else {
            unset($closedtags[array_search($openedtags[$i], $closedtags)]);
        }
    }
    return $html;
}

/**
 * 导出数据为excel表格
 *@param $data    一个二维数组,结构如同从数据库查出来的数组
 *@param $title   excel的第一行标题,一个数组,如果为空则没有标题
 *@param $filename 下载的文件名
 *@examlpe
 $stu = M ('User');
 $arr = $stu -> select();
 exportexcel($arr,array('id','账户','密码','昵称'),'文件名!');
 */
function exportexcel($data=array(),$title=array(),$filename='report'){
    header("Content-type:application/octet-stream");
    header("Accept-Ranges:bytes");
    header("Content-type:application/vnd.ms-excel");
    header("Content-Disposition:attachment;filename=".$filename.".xls");
    header("Pragma: no-cache");
    header("Expires: 0");
    //导出xls 开始
    if (!empty($title)){
        foreach ($title as $k => $v) {
            $title[$k]=iconv("UTF-8", "GB2312",$v);
        }
        $title= implode("\t", $title);
        echo "$title\n";
    }
    if (!empty($data)){
        foreach($data as $key=>$val){
            foreach ($val as $ck => $cv) {
                $data[$key][$ck]=iconv("UTF-8", "GB2312", $cv);
            }
            $data[$key]=implode("\t", $data[$key]);

        }
        echo implode("\n",$data);
    }
}
function convert_cj($str='')
{
	$num=0;
	if($str=="优秀")
		$num=1;
	if($str=="良好")
		$num=2;
	if($str=="及格")
		$num=3;
	return $num;
}
function convert_time($time="1997-10-10")
{
	$year=((int)mb_substr($time,0,4, 'utf-8'));//取得年份
	$month=((int)mb_substr($time,5,2, 'utf-8'));//取得月份
	$day=((int)mb_substr($time,8,2, 'utf-8'));//取得几号
	$time= mktime(0,0,0,$month,$day,$year);
	return $time;
}

function dbhelper_array($array)
{
	$result=array();
	foreach($array as $k => $v)
	{
		if($v===''||$v===null)
			continue;
		$result[$k]=$v;
	}
	return $result;
}
function jpushSend($tag,$msg,$title,$data)
{
	$pushurl='http://www.mooots.com/vendor/xhtpush.php';
	$json=tojson($data);
	$pdata=array(
			"tag"=>$tag,
			"type"=>1,
			"content"=>t(hf($msg)),
			"title"=>$title,
			"json"=>$json
	);
	curl_post_contents($pushurl, $pdata);
}
function jljpush($json=array(),$send='')
{
	global $new;
	if(isset($json['shid']))
	{
		$shname=$new['api']->find("xht_school",array("shid"=>$json['shid']));
		$shname=$shname['shname'];
		$json['shname']=$shname;
	}
	$id=$new['api']->create("xht_jl_jpush",$json);
	$json['id']=$id;
	$json['ctime']=date('Y年m月d日 H:i',$json['ctime']);
	$pushurl='http://www.mooots.com/vendor/xhtcjpush.php';
	$json=tojson($json);
	$pdata=array(
			'rid'=>'["'.$send.'"]',
			"type"=>4,
			"json"=>$json,
	);
	$result=curl_post_contents($pushurl, $pdata);
	return $result;
}
function upfileCheckType($files,$uptype)
{
	$arrType = explode ( '.', strtolower ( $files ['name'] ) ); // 转小写一下
	$type = array_pop ( $arrType );
	if (in_array ( $type, $uptype )) {
		return true;
	}
	return false;
}
function upFTP($files,$path,$type)
{
	global $TS_COMM_URL;
	ignore_user_abort();
	set_time_limit(0);
	$host=$TS_COMM_URL['UMS']['FTP'];
	$fuser=$TS_COMM_URL['UMS']['fuser'];
	$fpass=$TS_COMM_URL['UMS']['fpass'];
	$uid=$path;
	$conn=ftp_connect($host);
	if(!$conn)
	{
		return "FTP连接错误";
	}
	$login=ftp_login($conn, $fuser, $fpass);
	if(!$login)
	{
		return "FTP用户名密码错误";
	}

	$cdir=ftp_pwd($conn);
	if (!@ftp_chdir($conn, $uid)){
		if(!ftp_mkdir($conn, $uid)){
			return '远程服务器权限错误';
		}
	}
	if(!ftp_chdir($conn, $cdir)){
		return '远程服务器权限错误1';
	}
	ftp_pasv($conn,true);
	$path=$path.'/'.time().'.'.$type;
	if(!ftp_put($conn, $path, $files, FTP_BINARY)){
		return '上传错误，请重新上传';
	}
	ftp_close($conn);
	$result['url']=$TS_COMM_URL['UMS']['domain'].'/'.$path;
	return $result;
}
